@causyne/agent 1.20.81 → 1.20.83

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.81",
3
+ "version": "1.20.83",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -1,9 +1,10 @@
1
1
  // Continuum TUI Picker: interactive modal dialog for browsing and adopting peer agent sessions.
2
2
  // Authorship: Strict TypeScript (Causyne Agent).
3
3
  // @ts-expect-error untyped local TUI dialogs
4
- import { SelectLayer, TextLayer } from '../../tui/dialogs.js';
4
+ import { TextLayer } from '../../tui/dialogs.js';
5
5
  // @ts-expect-error untyped local TUI theme
6
6
  import { GLYPHS } from '../../tui/theme.js';
7
+ import { ContinuumPickerLayer } from './continuumPickerView.js';
7
8
  import { ContinuumScanner } from '../scanner.js';
8
9
  import { adoptContinuumSession } from '../ingest.js';
9
10
  function formatTimeAgo(timestamp) {
@@ -43,16 +44,26 @@ export async function runInteractiveContinuum(prompt, options = {}) {
43
44
  }
44
45
  const items = buildContinuumItems(sessions);
45
46
  const pickedSession = await new Promise((resolve) => {
46
- const layer = new SelectLayer({
47
- title: `Continuum · Cross-Agent Sessions (${sessions.length})`,
48
- placeholder: 'search past agent conversations (antigravity, opencode, codex, claude)...',
49
- emptyText: 'no matching sessions found',
50
- width: 78,
51
- height: 20,
52
- footer: `enter adopt session ${GLYPHS.dot} esc cancel`,
53
- items,
54
- onPick: (item) => {
55
- resolve(item ? item.value : null);
47
+ const layer = new ContinuumPickerLayer({
48
+ sessions: items,
49
+ onPick: (item) => resolve(item?.value || null),
50
+ onPreview: (session) => {
51
+ void openContinuumPreview(session.id, prompt, scanner)
52
+ .then((opened) => {
53
+ if (!opened)
54
+ prompt.openLayer(new TextLayer({
55
+ title: 'Continuum · Preview unavailable',
56
+ lines: ['This session could not be loaded.', 'It may have moved or been deleted.'],
57
+ width: 72,
58
+ height: 9
59
+ }));
60
+ })
61
+ .catch(() => prompt.openLayer(new TextLayer({
62
+ title: 'Continuum · Preview unavailable',
63
+ lines: ['The source agent session could not be read.'],
64
+ width: 72,
65
+ height: 9
66
+ })));
56
67
  }
57
68
  });
58
69
  prompt.openLayer(layer);
@@ -2,9 +2,10 @@
2
2
  // Authorship: Strict TypeScript (Causyne Agent).
3
3
 
4
4
  // @ts-expect-error untyped local TUI dialogs
5
- import { SelectLayer, TextLayer } from '../../tui/dialogs.js';
5
+ import { TextLayer } from '../../tui/dialogs.js';
6
6
  // @ts-expect-error untyped local TUI theme
7
7
  import { GLYPHS } from '../../tui/theme.js';
8
+ import { ContinuumPickerLayer } from './continuumPickerView.js';
8
9
  import type { ContinuumSessionSummary } from '../types.js';
9
10
  import { ContinuumScanner } from '../scanner.js';
10
11
  import { adoptContinuumSession } from '../ingest.js';
@@ -63,16 +64,25 @@ export async function runInteractiveContinuum(
63
64
  const items = buildContinuumItems(sessions);
64
65
 
65
66
  const pickedSession = await new Promise<ContinuumSessionSummary | null>((resolve) => {
66
- const layer = new SelectLayer({
67
- title: `Continuum · Cross-Agent Sessions (${sessions.length})`,
68
- placeholder: 'search past agent conversations (antigravity, opencode, codex, claude)...',
69
- emptyText: 'no matching sessions found',
70
- width: 78,
71
- height: 20,
72
- footer: `enter adopt session ${GLYPHS.dot} esc cancel`,
73
- items,
74
- onPick: (item: { value: ContinuumSessionSummary } | null) => {
75
- resolve(item ? item.value : null);
67
+ const layer = new ContinuumPickerLayer({
68
+ sessions: items,
69
+ onPick: (item) => resolve(item?.value || null),
70
+ onPreview: (session) => {
71
+ void openContinuumPreview(session.id, prompt, scanner)
72
+ .then((opened) => {
73
+ if (!opened) prompt.openLayer(new TextLayer({
74
+ title: 'Continuum · Preview unavailable',
75
+ lines: ['This session could not be loaded.', 'It may have moved or been deleted.'],
76
+ width: 72,
77
+ height: 9
78
+ }));
79
+ })
80
+ .catch(() => prompt.openLayer(new TextLayer({
81
+ title: 'Continuum · Preview unavailable',
82
+ lines: ['The source agent session could not be read.'],
83
+ width: 72,
84
+ height: 9
85
+ })));
76
86
  }
77
87
  });
78
88
  prompt.openLayer(layer);
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Causyne Continuum: provider-aware, keyboard-operated session browser.
3
+ * This is a presentation-only layer over the existing SelectLayer/SelectList.
4
+ * No adapter, journal, tool policy or adoption behavior is changed here.
5
+ */
6
+ // @ts-expect-error The existing dialog component is implemented in JavaScript.
7
+ import { SelectLayer } from '../../tui/dialogs.js';
8
+ // @ts-expect-error The existing theme is implemented in JavaScript.
9
+ import { bold, dim, paint, GLYPHS } from '../../tui/theme.js';
10
+ import { safeDisplay, truncate, visibleWidth } from '../../tui/text.js';
11
+ const MAX_PANEL_HEIGHT = 34;
12
+ const MIN_DETAIL_WIDTH = 46;
13
+ const SOURCE_ORDER = [
14
+ 'codex', 'antigravity', 'opencode', 'claude_code', 'causyne', 'cursor'
15
+ ];
16
+ const PLATFORM_NAMES = {
17
+ codex: 'Codex',
18
+ antigravity: 'Antigravity',
19
+ opencode: 'OpenCode',
20
+ claude_code: 'Claude Code',
21
+ causyne: 'Causyne',
22
+ cursor: 'Cursor'
23
+ };
24
+ function clean(value) {
25
+ // safeDisplay strips control sequences that could corrupt a terminal frame.
26
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
27
+ }
28
+ function shortWorkspace(value) {
29
+ const path = clean(value).replace(/\\/g, '/').replace(/\/+$/, '');
30
+ if (!path)
31
+ return 'Unknown workspace';
32
+ const parts = path.split('/').filter(Boolean);
33
+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : path;
34
+ }
35
+ function relativeTime(timestamp, now) {
36
+ if (!Number.isFinite(timestamp) || timestamp <= 0)
37
+ return 'unknown';
38
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
39
+ if (seconds < 60)
40
+ return 'now';
41
+ if (seconds < 3600)
42
+ return `${Math.floor(seconds / 60)}m`;
43
+ if (seconds < 86400)
44
+ return `${Math.floor(seconds / 3600)}h`;
45
+ if (seconds < 7 * 86400)
46
+ return `${Math.floor(seconds / 86400)}d`;
47
+ return `${Math.floor(seconds / (7 * 86400))}w`;
48
+ }
49
+ function countLabel(count) {
50
+ if (!Number.isFinite(count) || count < 0)
51
+ return '0 msgs';
52
+ return `${Math.floor(count).toLocaleString('en-US')} ${count === 1 ? 'msg' : 'msgs'}`;
53
+ }
54
+ /** Fit two pieces of styled text in one terminal row, retaining the left title. */
55
+ function pairedRow(left, right, columns) {
56
+ const width = Math.max(1, Math.floor(columns));
57
+ const rightWidth = visibleWidth(right);
58
+ if (!right || width < 45 || rightWidth > width - 20)
59
+ return truncate(left, width, '…');
60
+ const title = truncate(left, Math.max(1, width - rightWidth - 2), '…');
61
+ return title + ' '.repeat(Math.max(1, width - visibleWidth(title) - rightWidth)) + right;
62
+ }
63
+ function sourceName(value) {
64
+ return clean(value.sourceLabel) || PLATFORM_NAMES[value.sourcePlatform] || 'Other';
65
+ }
66
+ /**
67
+ * Group by agent with recency inside each source. A stable tie-breaker means
68
+ * the selected session never jumps unpredictably between redraws.
69
+ */
70
+ export function sortContinuumItems(items) {
71
+ const order = new Map(SOURCE_ORDER.map((platform, index) => [platform, index]));
72
+ return [...items].sort((a, b) => {
73
+ const groupA = order.get(a.value.sourcePlatform) ?? SOURCE_ORDER.length;
74
+ const groupB = order.get(b.value.sourcePlatform) ?? SOURCE_ORDER.length;
75
+ return groupA - groupB
76
+ || (Number(b.value.updatedAt) || 0) - (Number(a.value.updatedAt) || 0)
77
+ || a.value.id.localeCompare(b.value.id);
78
+ });
79
+ }
80
+ function renderedItem(item, selected, width, now) {
81
+ const title = clean(item.value.title) || 'Untitled session';
82
+ const prefix = selected ? ` ${paint('accent', '▸')} ` : ' ';
83
+ const stats = dim(`${countLabel(item.value.messageCount)} ${GLYPHS.dot} ${relativeTime(item.value.updatedAt, now)}`);
84
+ const headline = pairedRow(prefix + (selected ? bold(paint('ink', title)) : paint('ink', title)), stats, width);
85
+ const workspace = clean(item.value.workspacePath);
86
+ const sub = ` ${dim(shortWorkspace(workspace))}`;
87
+ return [truncate(headline, width, '…'), truncate(sub, width, '…')];
88
+ }
89
+ /**
90
+ * Render a viewport of category headings + TWO-row session entries.
91
+ * Headers never occupy the only remaining row; selected items stay visible.
92
+ */
93
+ export function renderContinuumWindow(entries, start, selected, width, budget, now = Date.now()) {
94
+ const rows = [];
95
+ const safeWidth = Math.max(1, Math.floor(width));
96
+ const allowed = Math.max(0, Math.floor(budget));
97
+ let lastIndex = start - 1;
98
+ let itemCount = 0;
99
+ let previousGroup = null;
100
+ for (let index = start; index < entries.length; index++) {
101
+ const item = entries[index]?.item;
102
+ if (!item)
103
+ continue;
104
+ const group = sourceName(item.value);
105
+ const needHeader = group !== previousGroup;
106
+ const needed = 2 + (needHeader ? 1 : 0);
107
+ if (rows.length + needed > allowed) {
108
+ // With only two rows remaining, show the item without an orphaned header.
109
+ if (!(needHeader && rows.length + 2 <= allowed))
110
+ break;
111
+ }
112
+ else if (needHeader) {
113
+ rows.push(dim(` ${truncate(group.toUpperCase(), Math.max(1, safeWidth - 5), '…')}`));
114
+ }
115
+ rows.push(...renderedItem(item, index === selected, safeWidth, now));
116
+ lastIndex = index;
117
+ itemCount++;
118
+ previousGroup = group;
119
+ }
120
+ return { rows, firstIndex: start, lastIndex, itemCount };
121
+ }
122
+ export class ContinuumPickerLayer extends SelectLayer {
123
+ items;
124
+ scopes;
125
+ onPreview;
126
+ scopeIndex = 0;
127
+ visibleItems = 5;
128
+ constructor(options) {
129
+ const items = sortContinuumItems(options.sessions);
130
+ super({
131
+ title: `Continuum · ${items.length} recent cross-agent sessions`,
132
+ width: 112,
133
+ height: MAX_PANEL_HEIGHT,
134
+ footer: `↑↓ move ${GLYPHS.dot} tab source ${GLYPHS.dot} F2 preview ${GLYPHS.dot} enter adopt ${GLYPHS.dot} esc close`,
135
+ placeholder: 'Search sessions, projects, or IDs',
136
+ emptyText: 'No matching sessions',
137
+ items,
138
+ onPick: options.onPick
139
+ });
140
+ this.items = items;
141
+ this.scopes = ['all', ...SOURCE_ORDER.filter(platform => items.some(item => item.value.sourcePlatform === platform))];
142
+ this.onPreview = options.onPreview;
143
+ }
144
+ get scope() { return this.scopes[this.scopeIndex] ?? 'all'; }
145
+ get availableScopes() { return this.scopes; }
146
+ preferredHeight() {
147
+ // No fixed 34-row empty frame when the machine has only a few sessions.
148
+ const items = this.list.filtered.length;
149
+ const categories = new Set(this.list.filtered.map(({ item }) => sourceName(item.value))).size;
150
+ return Math.min(MAX_PANEL_HEIGHT, Math.max(12, 3 + 4 + 2 + items * 2 + categories));
151
+ }
152
+ setScope(direction) {
153
+ const oldId = this.list.current?.value.id;
154
+ this.scopeIndex = (this.scopeIndex + direction + this.scopes.length) % this.scopes.length;
155
+ const scope = this.scope;
156
+ const chosen = scope === 'all' ? this.items :
157
+ this.items.filter(item => item.value.sourcePlatform === scope);
158
+ const query = this.list.query;
159
+ this.list.setItems(chosen);
160
+ this.list.query = query;
161
+ this.list.refilter();
162
+ const preserved = this.list.filtered.findIndex(({ item }) => item.value.id === oldId);
163
+ this.list.selected = preserved >= 0 ? preserved : 0;
164
+ this.list.offset = 0;
165
+ }
166
+ key(event) {
167
+ if (!event)
168
+ return null;
169
+ if (event.name === 'tab') {
170
+ this.setScope(event.shift ? -1 : 1);
171
+ return 'handled';
172
+ }
173
+ if (event.name === 'f2') {
174
+ const current = this.list.current;
175
+ if (current && this.onPreview)
176
+ this.onPreview(current.value);
177
+ return 'handled';
178
+ }
179
+ if (event.name === 'pageup' || event.name === 'pagedown') {
180
+ const direction = event.name === 'pageup' ? -1 : 1;
181
+ this.list.moveTo(this.list.selected + direction * Math.max(1, this.visibleItems - 1), Math.max(1, this.visibleItems));
182
+ return 'handled';
183
+ }
184
+ const query = this.list.query;
185
+ const result = super.key(event);
186
+ if (this.list.query !== query) {
187
+ this.list.selected = 0;
188
+ this.list.offset = 0;
189
+ }
190
+ return result;
191
+ }
192
+ body(width, height) {
193
+ const w = Math.max(8, Math.floor(width));
194
+ const h = Math.max(1, Math.floor(height));
195
+ const rows = [];
196
+ const scope = this.scope;
197
+ const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
198
+ const filtered = this.list.filtered;
199
+ const count = filtered.length;
200
+ const total = this.items.length;
201
+ const narrow = w < MIN_DETAIL_WIDTH;
202
+ const sourceText = ` ${paint('accent', label.toUpperCase())}`;
203
+ rows.push(pairedRow(sourceText, w >= 49 ? dim(`${count} / ${total} sessions ${this.scopeIndex + 1}/${this.scopes.length} sources`) : '', w));
204
+ const lead = ` ${paint('accent', GLYPHS.arrow)} `;
205
+ const room = Math.max(1, w - visibleWidth(lead) - 1);
206
+ const query = clean(this.list.query);
207
+ let tail = query;
208
+ while (visibleWidth(tail) > room)
209
+ tail = [...tail].slice(1).join('');
210
+ const shown = tail || dim(narrow ? 'Search sessions...' : 'Search by title, project, provider, or ID...');
211
+ rows.push(lead + truncate(shown, room, '…'));
212
+ this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + visibleWidth(tail)), y: 1 };
213
+ rows.push(paint('rule', '─'.repeat(w)));
214
+ // Small terminals favor visible list navigation over the detail inspector.
215
+ const details = h >= 18 ? 5 : h >= 12 ? 3 : h >= 9 ? 1 : 0;
216
+ const budget = Math.max(0, h - 3 - details);
217
+ if (budget > 0 && count === 0) {
218
+ rows.push('');
219
+ if (rows.length < h - details)
220
+ rows.push(dim(' No sessions match this filter.'));
221
+ if (rows.length < h - details)
222
+ rows.push(dim(' Tab changes source. Ctrl+U clears search.'));
223
+ }
224
+ else if (budget > 0) {
225
+ const selected = Math.min(Math.max(0, this.list.selected), count - 1);
226
+ let from = Math.min(Math.max(0, this.list.offset), selected);
227
+ let output = renderContinuumWindow(filtered, from, selected, w, budget);
228
+ while (output.lastIndex < selected && from < selected) {
229
+ from++;
230
+ output = renderContinuumWindow(filtered, from, selected, w, budget);
231
+ }
232
+ this.list.offset = from;
233
+ this.visibleItems = Math.max(1, output.itemCount);
234
+ this.list.lastItemRows = Math.max(1, this.visibleItems);
235
+ rows.push(...output.rows);
236
+ }
237
+ while (rows.length < h - details)
238
+ rows.push('');
239
+ const selected = this.list.current?.value;
240
+ if (details > 0) {
241
+ rows.push(paint('rule', '─'.repeat(w)));
242
+ }
243
+ if (details >= 3) {
244
+ const heading = selected ? ` ${sourceName(selected)}` : ' No session selected';
245
+ const countText = selected ? dim(countLabel(selected.messageCount)) : '';
246
+ rows.push(pairedRow(heading, countText, w));
247
+ rows.push(dim(' ' + truncate(selected ? shortWorkspace(selected.workspacePath) : 'Change the source or search query.', Math.max(1, w - 3), '…')));
248
+ }
249
+ if (details >= 5) {
250
+ const snippet = selected ? clean(selected.snippet) : '';
251
+ rows.push(dim(' ' + truncate(snippet || 'No excerpt available', Math.max(1, w - 3), '…')));
252
+ const id = selected ? clean(selected.id) : '';
253
+ rows.push(dim(' ' + truncate(id || 'No session ID', Math.max(1, w - 3), '…')));
254
+ }
255
+ while (rows.length < h)
256
+ rows.push('');
257
+ return rows.slice(0, h).map(row => truncate(row, w, '…'));
258
+ }
259
+ }
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Causyne Continuum: provider-aware, keyboard-operated session browser.
3
+ * This is a presentation-only layer over the existing SelectLayer/SelectList.
4
+ * No adapter, journal, tool policy or adoption behavior is changed here.
5
+ */
6
+ // @ts-expect-error The existing dialog component is implemented in JavaScript.
7
+ import { SelectLayer } from '../../tui/dialogs.js';
8
+ // @ts-expect-error The existing theme is implemented in JavaScript.
9
+ import { bold, dim, paint, GLYPHS } from '../../tui/theme.js';
10
+ import { safeDisplay, truncate, visibleWidth } from '../../tui/text.js';
11
+ import type { AgentPlatform, ContinuumSessionSummary } from '../types.js';
12
+
13
+ export interface ContinuumPickerItem {
14
+ label: string;
15
+ category: string;
16
+ description: string;
17
+ searchText: string;
18
+ hint?: string;
19
+ value: ContinuumSessionSummary;
20
+ }
21
+
22
+ export interface ContinuumPickerViewOptions {
23
+ sessions: ContinuumPickerItem[];
24
+ onPick: (item: ContinuumPickerItem | null) => void;
25
+ onPreview?: (session: ContinuumSessionSummary) => void;
26
+ }
27
+
28
+ interface KeyEvent {
29
+ name?: string;
30
+ ctrl?: boolean;
31
+ shift?: boolean;
32
+ meta?: boolean;
33
+ sequence?: string;
34
+ text?: string;
35
+ }
36
+
37
+ interface FilteredEntry { item: ContinuumPickerItem; }
38
+ interface ListWindow {
39
+ rows: string[];
40
+ firstIndex: number;
41
+ lastIndex: number;
42
+ itemCount: number;
43
+ }
44
+
45
+ const MAX_PANEL_HEIGHT = 34;
46
+ const MIN_DETAIL_WIDTH = 46;
47
+ const SOURCE_ORDER: AgentPlatform[] = [
48
+ 'codex', 'antigravity', 'opencode', 'claude_code', 'causyne', 'cursor'
49
+ ];
50
+ const PLATFORM_NAMES: Record<AgentPlatform, string> = {
51
+ codex: 'Codex',
52
+ antigravity: 'Antigravity',
53
+ opencode: 'OpenCode',
54
+ claude_code: 'Claude Code',
55
+ causyne: 'Causyne',
56
+ cursor: 'Cursor'
57
+ };
58
+
59
+ type Scope = AgentPlatform | 'all';
60
+
61
+ function clean(value: unknown): string {
62
+ // safeDisplay strips control sequences that could corrupt a terminal frame.
63
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
64
+ }
65
+
66
+ function shortWorkspace(value: string): string {
67
+ const path = clean(value).replace(/\\/g, '/').replace(/\/+$/, '');
68
+ if (!path) return 'Unknown workspace';
69
+ const parts = path.split('/').filter(Boolean);
70
+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : path;
71
+ }
72
+
73
+ function relativeTime(timestamp: number, now: number): string {
74
+ if (!Number.isFinite(timestamp) || timestamp <= 0) return 'unknown';
75
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
76
+ if (seconds < 60) return 'now';
77
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
78
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
79
+ if (seconds < 7 * 86400) return `${Math.floor(seconds / 86400)}d`;
80
+ return `${Math.floor(seconds / (7 * 86400))}w`;
81
+ }
82
+
83
+ function countLabel(count: number): string {
84
+ if (!Number.isFinite(count) || count < 0) return '0 msgs';
85
+ return `${Math.floor(count).toLocaleString('en-US')} ${count === 1 ? 'msg' : 'msgs'}`;
86
+ }
87
+
88
+ /** Fit two pieces of styled text in one terminal row, retaining the left title. */
89
+ function pairedRow(left: string, right: string, columns: number): string {
90
+ const width = Math.max(1, Math.floor(columns));
91
+ const rightWidth = visibleWidth(right);
92
+ if (!right || width < 45 || rightWidth > width - 20) return truncate(left, width, '…');
93
+ const title = truncate(left, Math.max(1, width - rightWidth - 2), '…');
94
+ return title + ' '.repeat(Math.max(1, width - visibleWidth(title) - rightWidth)) + right;
95
+ }
96
+
97
+ function sourceName(value: ContinuumSessionSummary): string {
98
+ return clean(value.sourceLabel) || PLATFORM_NAMES[value.sourcePlatform] || 'Other';
99
+ }
100
+
101
+ /**
102
+ * Group by agent with recency inside each source. A stable tie-breaker means
103
+ * the selected session never jumps unpredictably between redraws.
104
+ */
105
+ export function sortContinuumItems(items: ContinuumPickerItem[]): ContinuumPickerItem[] {
106
+ const order = new Map(SOURCE_ORDER.map((platform, index) => [platform, index]));
107
+ return [...items].sort((a, b) => {
108
+ const groupA = order.get(a.value.sourcePlatform) ?? SOURCE_ORDER.length;
109
+ const groupB = order.get(b.value.sourcePlatform) ?? SOURCE_ORDER.length;
110
+ return groupA - groupB
111
+ || (Number(b.value.updatedAt) || 0) - (Number(a.value.updatedAt) || 0)
112
+ || a.value.id.localeCompare(b.value.id);
113
+ });
114
+ }
115
+
116
+ function renderedItem(
117
+ item: ContinuumPickerItem, selected: boolean, width: number, now: number
118
+ ): string[] {
119
+ const title = clean(item.value.title) || 'Untitled session';
120
+ const prefix = selected ? ` ${paint('accent', '▸')} ` : ' ';
121
+ const stats = dim(`${countLabel(item.value.messageCount)} ${GLYPHS.dot} ${relativeTime(item.value.updatedAt, now)}`);
122
+ const headline = pairedRow(
123
+ prefix + (selected ? bold(paint('ink', title)) : paint('ink', title)), stats, width
124
+ );
125
+ const workspace = clean(item.value.workspacePath);
126
+ const sub = ` ${dim(shortWorkspace(workspace))}`;
127
+ return [truncate(headline, width, '…'), truncate(sub, width, '…')];
128
+ }
129
+
130
+ /**
131
+ * Render a viewport of category headings + TWO-row session entries.
132
+ * Headers never occupy the only remaining row; selected items stay visible.
133
+ */
134
+ export function renderContinuumWindow(
135
+ entries: FilteredEntry[], start: number, selected: number,
136
+ width: number, budget: number, now = Date.now()
137
+ ): ListWindow {
138
+ const rows: string[] = [];
139
+ const safeWidth = Math.max(1, Math.floor(width));
140
+ const allowed = Math.max(0, Math.floor(budget));
141
+ let lastIndex = start - 1;
142
+ let itemCount = 0;
143
+ let previousGroup: string | null = null;
144
+ for (let index = start; index < entries.length; index++) {
145
+ const item = entries[index]?.item;
146
+ if (!item) continue;
147
+ const group = sourceName(item.value);
148
+ const needHeader = group !== previousGroup;
149
+ const needed = 2 + (needHeader ? 1 : 0);
150
+ if (rows.length + needed > allowed) {
151
+ // With only two rows remaining, show the item without an orphaned header.
152
+ if (!(needHeader && rows.length + 2 <= allowed)) break;
153
+ } else if (needHeader) {
154
+ rows.push(dim(` ${truncate(group.toUpperCase(), Math.max(1, safeWidth - 5), '…')}`));
155
+ }
156
+ rows.push(...renderedItem(item, index === selected, safeWidth, now));
157
+ lastIndex = index;
158
+ itemCount++;
159
+ previousGroup = group;
160
+ }
161
+ return { rows, firstIndex: start, lastIndex, itemCount };
162
+ }
163
+
164
+ export class ContinuumPickerLayer extends SelectLayer {
165
+ // Inherited instance fields from the existing JavaScript SelectLayer.
166
+ declare list: {
167
+ all: ContinuumPickerItem[];
168
+ filtered: FilteredEntry[];
169
+ selected: number;
170
+ offset: number;
171
+ query: string;
172
+ current: ContinuumPickerItem | null;
173
+ lastItemRows?: number;
174
+ setItems(items: ContinuumPickerItem[]): void;
175
+ moveTo(index: number, visibleRows: number): void;
176
+ refilter(): void;
177
+ };
178
+ declare cursor: { x: number; y: number } | null;
179
+ private readonly items: ContinuumPickerItem[];
180
+ private readonly scopes: Scope[];
181
+ private readonly onPreview: ((session: ContinuumSessionSummary) => void) | undefined;
182
+ private scopeIndex = 0;
183
+ private visibleItems = 5;
184
+
185
+ constructor(options: ContinuumPickerViewOptions) {
186
+ const items = sortContinuumItems(options.sessions);
187
+ super({
188
+ title: `Continuum · ${items.length} recent cross-agent sessions`,
189
+ width: 112,
190
+ height: MAX_PANEL_HEIGHT,
191
+ footer: `↑↓ move ${GLYPHS.dot} tab source ${GLYPHS.dot} F2 preview ${GLYPHS.dot} enter adopt ${GLYPHS.dot} esc close`,
192
+ placeholder: 'Search sessions, projects, or IDs',
193
+ emptyText: 'No matching sessions',
194
+ items,
195
+ onPick: options.onPick
196
+ });
197
+ this.items = items;
198
+ this.scopes = ['all', ...SOURCE_ORDER.filter(platform =>
199
+ items.some(item => item.value.sourcePlatform === platform))];
200
+ this.onPreview = options.onPreview;
201
+ }
202
+
203
+ get scope(): Scope { return this.scopes[this.scopeIndex] ?? 'all'; }
204
+ get availableScopes(): readonly Scope[] { return this.scopes; }
205
+
206
+ preferredHeight(): number {
207
+ // No fixed 34-row empty frame when the machine has only a few sessions.
208
+ const items = this.list.filtered.length;
209
+ const categories = new Set(this.list.filtered.map(({ item }: FilteredEntry) => sourceName(item.value))).size;
210
+ return Math.min(MAX_PANEL_HEIGHT, Math.max(12, 3 + 4 + 2 + items * 2 + categories));
211
+ }
212
+
213
+ private setScope(direction: number): void {
214
+ const oldId = this.list.current?.value.id;
215
+ this.scopeIndex = (this.scopeIndex + direction + this.scopes.length) % this.scopes.length;
216
+ const scope = this.scope;
217
+ const chosen = scope === 'all' ? this.items :
218
+ this.items.filter(item => item.value.sourcePlatform === scope);
219
+ const query = this.list.query;
220
+ this.list.setItems(chosen);
221
+ this.list.query = query;
222
+ this.list.refilter();
223
+ const preserved = this.list.filtered.findIndex(({ item }: FilteredEntry) => item.value.id === oldId);
224
+ this.list.selected = preserved >= 0 ? preserved : 0;
225
+ this.list.offset = 0;
226
+ }
227
+
228
+ key(event: KeyEvent | null): string | null {
229
+ if (!event) return null;
230
+ if (event.name === 'tab') {
231
+ this.setScope(event.shift ? -1 : 1);
232
+ return 'handled';
233
+ }
234
+ if (event.name === 'f2') {
235
+ const current = this.list.current;
236
+ if (current && this.onPreview) this.onPreview(current.value);
237
+ return 'handled';
238
+ }
239
+ if (event.name === 'pageup' || event.name === 'pagedown') {
240
+ const direction = event.name === 'pageup' ? -1 : 1;
241
+ this.list.moveTo(this.list.selected + direction * Math.max(1, this.visibleItems - 1),
242
+ Math.max(1, this.visibleItems));
243
+ return 'handled';
244
+ }
245
+ const query = this.list.query;
246
+ const result = super.key(event);
247
+ if (this.list.query !== query) {
248
+ this.list.selected = 0;
249
+ this.list.offset = 0;
250
+ }
251
+ return result;
252
+ }
253
+
254
+ body(width: number, height: number): string[] {
255
+ const w = Math.max(8, Math.floor(width));
256
+ const h = Math.max(1, Math.floor(height));
257
+ const rows: string[] = [];
258
+ const scope = this.scope;
259
+ const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
260
+ const filtered = this.list.filtered;
261
+ const count = filtered.length;
262
+ const total = this.items.length;
263
+ const narrow = w < MIN_DETAIL_WIDTH;
264
+
265
+ const sourceText = ` ${paint('accent', label.toUpperCase())}`;
266
+ rows.push(pairedRow(sourceText,
267
+ w >= 49 ? dim(`${count} / ${total} sessions ${this.scopeIndex + 1}/${this.scopes.length} sources`) : '', w));
268
+
269
+ const lead = ` ${paint('accent', GLYPHS.arrow)} `;
270
+ const room = Math.max(1, w - visibleWidth(lead) - 1);
271
+ const query = clean(this.list.query);
272
+ let tail = query;
273
+ while (visibleWidth(tail) > room) tail = [...tail].slice(1).join('');
274
+ const shown = tail || dim(narrow ? 'Search sessions...' : 'Search by title, project, provider, or ID...');
275
+ rows.push(lead + truncate(shown, room, '…'));
276
+ this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + visibleWidth(tail)), y: 1 };
277
+ rows.push(paint('rule', '─'.repeat(w)));
278
+
279
+ // Small terminals favor visible list navigation over the detail inspector.
280
+ const details = h >= 18 ? 5 : h >= 12 ? 3 : h >= 9 ? 1 : 0;
281
+ const budget = Math.max(0, h - 3 - details);
282
+ if (budget > 0 && count === 0) {
283
+ rows.push('');
284
+ if (rows.length < h - details) rows.push(dim(' No sessions match this filter.'));
285
+ if (rows.length < h - details) rows.push(dim(' Tab changes source. Ctrl+U clears search.'));
286
+ } else if (budget > 0) {
287
+ const selected = Math.min(Math.max(0, this.list.selected), count - 1);
288
+ let from = Math.min(Math.max(0, this.list.offset), selected);
289
+ let output = renderContinuumWindow(filtered, from, selected, w, budget);
290
+ while (output.lastIndex < selected && from < selected) {
291
+ from++;
292
+ output = renderContinuumWindow(filtered, from, selected, w, budget);
293
+ }
294
+ this.list.offset = from;
295
+ this.visibleItems = Math.max(1, output.itemCount);
296
+ this.list.lastItemRows = Math.max(1, this.visibleItems);
297
+ rows.push(...output.rows);
298
+ }
299
+ while (rows.length < h - details) rows.push('');
300
+
301
+ const selected = this.list.current?.value;
302
+ if (details > 0) {
303
+ rows.push(paint('rule', '─'.repeat(w)));
304
+ }
305
+ if (details >= 3) {
306
+ const heading = selected ? ` ${sourceName(selected)}` : ' No session selected';
307
+ const countText = selected ? dim(countLabel(selected.messageCount)) : '';
308
+ rows.push(pairedRow(heading, countText, w));
309
+ rows.push(dim(' ' + truncate(selected ? shortWorkspace(selected.workspacePath) : 'Change the source or search query.',
310
+ Math.max(1, w - 3), '…')));
311
+ }
312
+ if (details >= 5) {
313
+ const snippet = selected ? clean(selected.snippet) : '';
314
+ rows.push(dim(' ' + truncate(snippet || 'No excerpt available', Math.max(1, w - 3), '…')));
315
+ const id = selected ? clean(selected.id) : '';
316
+ rows.push(dim(' ' + truncate(id || 'No session ID', Math.max(1, w - 3), '…')));
317
+ }
318
+ while (rows.length < h) rows.push('');
319
+ return rows.slice(0, h).map(row => truncate(row, w, '…'));
320
+ }
321
+ }
@@ -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
- // @ts-expect-error untyped local TUI dialogs
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 SelectLayer({
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
  }
@@ -2,8 +2,7 @@
2
2
  // Authored in Strict TypeScript for Causyne Agent.
3
3
  // Source-available under BUSL-1.1.
4
4
 
5
- // @ts-expect-error untyped local TUI dialogs
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 SelectLayer({
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
+ }