mirror of
https://github.com/getcompanion-ai/co-mono.git
synced 2026-04-21 12:00:15 +00:00
feat(coding-agent): add resume scope toggle with async loading
- /resume and --resume now toggle between Current Folder and All sessions with Tab - SessionManager.list() and listAll() are now async with optional progress callback - Shows loading progress (e.g. Loading 5/42) while scanning sessions - SessionInfo.cwd field shows session working directory in All view - Lazy loading: All sessions only loaded when user presses Tab closes #619 Co-authored-by: Thomas Mustier <mustierthomas@gmail.com>
This commit is contained in:
parent
e8d91f2bd4
commit
302404684f
9 changed files with 263 additions and 117 deletions
|
|
@ -2,8 +2,14 @@
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
- `SessionManager.list()` and `SessionManager.listAll()` are now async, returning `Promise<SessionInfo[]>`. Callers must await them. ([#620](https://github.com/badlogic/pi-mono/pull/620) by [@tmustier](https://github.com/tmustier))
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- `/resume` selector now toggles between current-folder and all sessions with Tab, showing the session cwd in the All view.
|
- `/resume` selector now toggles between current-folder and all sessions with Tab, showing the session cwd in the All view and loading progress. ([#620](https://github.com/badlogic/pi-mono/pull/620) by [@tmustier](https://github.com/tmustier))
|
||||||
|
- `SessionManager.list()` and `SessionManager.listAll()` accept optional `onProgress` callback for progress updates
|
||||||
|
- `SessionInfo.cwd` field containing the session's working directory (empty string for old sessions)
|
||||||
|
- `SessionListProgress` type export for progress callbacks
|
||||||
- `/models` command to enable/disable models for Ctrl+P cycling. Changes persist to `enabledModels` in settings.json and take effect immediately. ([#626](https://github.com/badlogic/pi-mono/pull/626) by [@CarlosGtrz](https://github.com/CarlosGtrz))
|
- `/models` command to enable/disable models for Ctrl+P cycling. Changes persist to `enabledModels` in settings.json and take effect immediately. ([#626](https://github.com/badlogic/pi-mono/pull/626) by [@CarlosGtrz](https://github.com/CarlosGtrz))
|
||||||
- `model_select` extension hook fires when model changes via `/model`, model cycling, or session restore with `source` field and `previousModel` ([#628](https://github.com/badlogic/pi-mono/pull/628) by [@marckrenn](https://github.com/marckrenn))
|
- `model_select` extension hook fires when model changes via `/model`, model cycling, or session restore with `source` field and `previousModel` ([#628](https://github.com/badlogic/pi-mono/pull/628) by [@marckrenn](https://github.com/marckrenn))
|
||||||
- `ctx.ui.setWorkingMessage()` extension API to customize the "Working..." message during streaming ([#625](https://github.com/badlogic/pi-mono/pull/625) by [@nicobailon](https://github.com/nicobailon))
|
- `ctx.ui.setWorkingMessage()` extension API to customize the "Working..." message during streaming ([#625](https://github.com/badlogic/pi-mono/pull/625) by [@nicobailon](https://github.com/nicobailon))
|
||||||
|
|
|
||||||
|
|
@ -459,7 +459,7 @@ Sessions auto-save to `~/.pi/agent/sessions/` organized by working directory.
|
||||||
pi --continue # Continue most recent session
|
pi --continue # Continue most recent session
|
||||||
pi -c # Short form
|
pi -c # Short form
|
||||||
|
|
||||||
pi --resume # Browse and select from past sessions
|
pi --resume # Browse and select from past sessions (Tab to toggle Current Folder / All)
|
||||||
pi -r # Short form
|
pi -r # Short form
|
||||||
|
|
||||||
pi --no-session # Ephemeral mode (don't save)
|
pi --no-session # Ephemeral mode (don't save)
|
||||||
|
|
|
||||||
|
|
@ -636,12 +636,17 @@ const { session } = await createAgentSession({
|
||||||
sessionManager: SessionManager.open("/path/to/session.jsonl"),
|
sessionManager: SessionManager.open("/path/to/session.jsonl"),
|
||||||
});
|
});
|
||||||
|
|
||||||
// List available sessions
|
// List available sessions (async with optional progress callback)
|
||||||
const sessions = SessionManager.list(process.cwd());
|
const sessions = await SessionManager.list(process.cwd());
|
||||||
for (const info of sessions) {
|
for (const info of sessions) {
|
||||||
console.log(`${info.id}: ${info.firstMessage} (${info.messageCount} messages)`);
|
console.log(`${info.id}: ${info.firstMessage} (${info.messageCount} messages, cwd: ${info.cwd})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// List all sessions across all projects
|
||||||
|
const allSessions = await SessionManager.listAll((loaded, total) => {
|
||||||
|
console.log(`Loading ${loaded}/${total}...`);
|
||||||
|
});
|
||||||
|
|
||||||
// Custom session directory (no cwd encoding)
|
// Custom session directory (no cwd encoding)
|
||||||
const customDir = "/path/to/my-sessions";
|
const customDir = "/path/to/my-sessions";
|
||||||
const { session } = await createAgentSession({
|
const { session } = await createAgentSession({
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ if (modelFallbackMessage) console.log("Note:", modelFallbackMessage);
|
||||||
console.log("Continued session:", continued.sessionFile);
|
console.log("Continued session:", continued.sessionFile);
|
||||||
|
|
||||||
// List and open specific session
|
// List and open specific session
|
||||||
const sessions = SessionManager.list(process.cwd());
|
const sessions = await SessionManager.list(process.cwd());
|
||||||
console.log(`\nFound ${sessions.length} sessions:`);
|
console.log(`\nFound ${sessions.length} sessions:`);
|
||||||
for (const info of sessions.slice(0, 3)) {
|
for (const info of sessions.slice(0, 3)) {
|
||||||
console.log(` ${info.id.slice(0, 8)}... - "${info.firstMessage.slice(0, 30)}..."`);
|
console.log(` ${info.id.slice(0, 8)}... - "${info.firstMessage.slice(0, 30)}..."`);
|
||||||
|
|
|
||||||
|
|
@ -3,21 +3,23 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ProcessTerminal, TUI } from "@mariozechner/pi-tui";
|
import { ProcessTerminal, TUI } from "@mariozechner/pi-tui";
|
||||||
import type { SessionInfo } from "../core/session-manager.js";
|
import type { SessionInfo, SessionListProgress } from "../core/session-manager.js";
|
||||||
import { SessionSelectorComponent } from "../modes/interactive/components/session-selector.js";
|
import { SessionSelectorComponent } from "../modes/interactive/components/session-selector.js";
|
||||||
|
|
||||||
|
type SessionsLoader = (onProgress?: SessionListProgress) => Promise<SessionInfo[]>;
|
||||||
|
|
||||||
/** Show TUI session selector and return selected session path or null if cancelled */
|
/** Show TUI session selector and return selected session path or null if cancelled */
|
||||||
export async function selectSession(
|
export async function selectSession(
|
||||||
currentSessions: SessionInfo[],
|
currentSessionsLoader: SessionsLoader,
|
||||||
allSessions: SessionInfo[],
|
allSessionsLoader: SessionsLoader,
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const ui = new TUI(new ProcessTerminal());
|
const ui = new TUI(new ProcessTerminal());
|
||||||
let resolved = false;
|
let resolved = false;
|
||||||
|
|
||||||
const selector = new SessionSelectorComponent(
|
const selector = new SessionSelectorComponent(
|
||||||
currentSessions,
|
currentSessionsLoader,
|
||||||
allSessions,
|
allSessionsLoader,
|
||||||
(path: string) => {
|
(path: string) => {
|
||||||
if (!resolved) {
|
if (!resolved) {
|
||||||
resolved = true;
|
resolved = true;
|
||||||
|
|
@ -36,6 +38,7 @@ export async function selectSession(
|
||||||
ui.stop();
|
ui.stop();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
},
|
},
|
||||||
|
() => ui.requestRender(),
|
||||||
);
|
);
|
||||||
|
|
||||||
ui.addChild(selector);
|
ui.addChild(selector);
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import {
|
||||||
statSync,
|
statSync,
|
||||||
writeFileSync,
|
writeFileSync,
|
||||||
} from "fs";
|
} from "fs";
|
||||||
|
import { readdir, readFile, stat } from "fs/promises";
|
||||||
import { join, resolve } from "path";
|
import { join, resolve } from "path";
|
||||||
import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
|
import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
|
||||||
import {
|
import {
|
||||||
|
|
@ -156,7 +157,8 @@ export interface SessionContext {
|
||||||
export interface SessionInfo {
|
export interface SessionInfo {
|
||||||
path: string;
|
path: string;
|
||||||
id: string;
|
id: string;
|
||||||
cwd?: string;
|
/** Working directory where the session was started. Empty string for old sessions. */
|
||||||
|
cwd: string;
|
||||||
created: Date;
|
created: Date;
|
||||||
modified: Date;
|
modified: Date;
|
||||||
messageCount: number;
|
messageCount: number;
|
||||||
|
|
@ -486,14 +488,26 @@ function extractTextContent(message: Message): string {
|
||||||
.join(" ");
|
.join(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildSessionInfo(filePath: string): SessionInfo | null {
|
async function buildSessionInfo(filePath: string): Promise<SessionInfo | null> {
|
||||||
const entries = loadEntriesFromFile(filePath);
|
try {
|
||||||
if (entries.length === 0) return null;
|
const content = await readFile(filePath, "utf8");
|
||||||
|
const entries: FileEntry[] = [];
|
||||||
|
const lines = content.trim().split("\n");
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
try {
|
||||||
|
entries.push(JSON.parse(line) as FileEntry);
|
||||||
|
} catch {
|
||||||
|
// Skip malformed lines
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries.length === 0) return null;
|
||||||
const header = entries[0];
|
const header = entries[0];
|
||||||
if (header.type !== "session") return null;
|
if (header.type !== "session") return null;
|
||||||
|
|
||||||
const stats = statSync(filePath);
|
const stats = await stat(filePath);
|
||||||
let messageCount = 0;
|
let messageCount = 0;
|
||||||
let firstMessage = "";
|
let firstMessage = "";
|
||||||
const allMessages: string[] = [];
|
const allMessages: string[] = [];
|
||||||
|
|
@ -502,7 +516,7 @@ function buildSessionInfo(filePath: string): SessionInfo | null {
|
||||||
if (entry.type !== "message") continue;
|
if (entry.type !== "message") continue;
|
||||||
messageCount++;
|
messageCount++;
|
||||||
|
|
||||||
const message = entry.message;
|
const message = (entry as SessionMessageEntry).message;
|
||||||
if (!isMessageWithContent(message)) continue;
|
if (!isMessageWithContent(message)) continue;
|
||||||
if (message.role !== "user" && message.role !== "assistant") continue;
|
if (message.role !== "user" && message.role !== "assistant") continue;
|
||||||
|
|
||||||
|
|
@ -515,40 +529,54 @@ function buildSessionInfo(filePath: string): SessionInfo | null {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const cwd = typeof header.cwd === "string" ? header.cwd : "";
|
const cwd = typeof (header as SessionHeader).cwd === "string" ? (header as SessionHeader).cwd : "";
|
||||||
|
|
||||||
return {
|
return {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
id: header.id,
|
id: (header as SessionHeader).id,
|
||||||
cwd,
|
cwd,
|
||||||
created: new Date(header.timestamp),
|
created: new Date((header as SessionHeader).timestamp),
|
||||||
modified: stats.mtime,
|
modified: stats.mtime,
|
||||||
messageCount,
|
messageCount,
|
||||||
firstMessage: firstMessage || "(no messages)",
|
firstMessage: firstMessage || "(no messages)",
|
||||||
allMessagesText: allMessages.join(" "),
|
allMessagesText: allMessages.join(" "),
|
||||||
};
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function listSessionsFromDir(dir: string): SessionInfo[] {
|
export type SessionListProgress = (loaded: number, total: number) => void;
|
||||||
|
|
||||||
|
async function listSessionsFromDir(
|
||||||
|
dir: string,
|
||||||
|
onProgress?: SessionListProgress,
|
||||||
|
progressOffset = 0,
|
||||||
|
progressTotal?: number,
|
||||||
|
): Promise<SessionInfo[]> {
|
||||||
const sessions: SessionInfo[] = [];
|
const sessions: SessionInfo[] = [];
|
||||||
if (!existsSync(dir)) {
|
if (!existsSync(dir)) {
|
||||||
return sessions;
|
return sessions;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const files = readdirSync(dir)
|
const dirEntries = await readdir(dir);
|
||||||
.filter((f) => f.endsWith(".jsonl"))
|
const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
|
||||||
.map((f) => join(dir, f));
|
const total = progressTotal ?? files.length;
|
||||||
|
|
||||||
for (const file of files) {
|
let loaded = 0;
|
||||||
try {
|
const results = await Promise.all(
|
||||||
const info = buildSessionInfo(file);
|
files.map(async (file) => {
|
||||||
|
const info = await buildSessionInfo(file);
|
||||||
|
loaded++;
|
||||||
|
onProgress?.(progressOffset + loaded, total);
|
||||||
|
return info;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
for (const info of results) {
|
||||||
if (info) {
|
if (info) {
|
||||||
sessions.push(info);
|
sessions.push(info);
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
// Skip files that can't be read
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Return empty list on error
|
// Return empty list on error
|
||||||
|
|
@ -1144,35 +1172,69 @@ export class SessionManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* List all sessions.
|
* List all sessions for a directory.
|
||||||
* @param cwd Working directory (used to compute default session directory)
|
* @param cwd Working directory (used to compute default session directory)
|
||||||
* @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
|
* @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
|
||||||
|
* @param onProgress Optional callback for progress updates (loaded, total)
|
||||||
*/
|
*/
|
||||||
static list(cwd: string, sessionDir?: string): SessionInfo[] {
|
static async list(cwd: string, sessionDir?: string, onProgress?: SessionListProgress): Promise<SessionInfo[]> {
|
||||||
const dir = sessionDir ?? getDefaultSessionDir(cwd);
|
const dir = sessionDir ?? getDefaultSessionDir(cwd);
|
||||||
const sessions = listSessionsFromDir(dir);
|
const sessions = await listSessionsFromDir(dir, onProgress);
|
||||||
sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
||||||
return sessions;
|
return sessions;
|
||||||
}
|
}
|
||||||
|
|
||||||
static listAll(): SessionInfo[] {
|
/**
|
||||||
const sessions: SessionInfo[] = [];
|
* List all sessions across all project directories.
|
||||||
|
* @param onProgress Optional callback for progress updates (loaded, total)
|
||||||
|
*/
|
||||||
|
static async listAll(onProgress?: SessionListProgress): Promise<SessionInfo[]> {
|
||||||
const sessionsDir = getSessionsDir();
|
const sessionsDir = getSessionsDir();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!existsSync(sessionsDir)) {
|
if (!existsSync(sessionsDir)) {
|
||||||
return sessions;
|
return [];
|
||||||
}
|
|
||||||
const entries = readdirSync(sessionsDir, { withFileTypes: true });
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (!entry.isDirectory()) continue;
|
|
||||||
sessions.push(...listSessionsFromDir(join(sessionsDir, entry.name)));
|
|
||||||
}
|
}
|
||||||
|
const entries = await readdir(sessionsDir, { withFileTypes: true });
|
||||||
|
const dirs = entries.filter((e) => e.isDirectory()).map((e) => join(sessionsDir, e.name));
|
||||||
|
|
||||||
|
// Count total files first for accurate progress
|
||||||
|
let totalFiles = 0;
|
||||||
|
const dirFiles: string[][] = [];
|
||||||
|
for (const dir of dirs) {
|
||||||
|
try {
|
||||||
|
const files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl"));
|
||||||
|
dirFiles.push(files.map((f) => join(dir, f)));
|
||||||
|
totalFiles += files.length;
|
||||||
} catch {
|
} catch {
|
||||||
// Return empty list on error
|
dirFiles.push([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process all files with progress tracking
|
||||||
|
let loaded = 0;
|
||||||
|
const sessions: SessionInfo[] = [];
|
||||||
|
const allFiles = dirFiles.flat();
|
||||||
|
|
||||||
|
const results = await Promise.all(
|
||||||
|
allFiles.map(async (file) => {
|
||||||
|
const info = await buildSessionInfo(file);
|
||||||
|
loaded++;
|
||||||
|
onProgress?.(loaded, totalFiles);
|
||||||
|
return info;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const info of results) {
|
||||||
|
if (info) {
|
||||||
|
sessions.push(info);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
|
||||||
return sessions;
|
return sessions;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -61,14 +61,14 @@ async function prepareInitialMessage(
|
||||||
* Resolve a session argument to a file path.
|
* Resolve a session argument to a file path.
|
||||||
* If it looks like a path, use as-is. Otherwise try to match as session ID prefix.
|
* If it looks like a path, use as-is. Otherwise try to match as session ID prefix.
|
||||||
*/
|
*/
|
||||||
function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): string {
|
async function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<string> {
|
||||||
// If it looks like a file path, use as-is
|
// If it looks like a file path, use as-is
|
||||||
if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) {
|
if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) {
|
||||||
return sessionArg;
|
return sessionArg;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to match as session ID (full or partial UUID)
|
// Try to match as session ID (full or partial UUID)
|
||||||
const sessions = SessionManager.list(cwd, sessionDir);
|
const sessions = await SessionManager.list(cwd, sessionDir);
|
||||||
const matches = sessions.filter((s) => s.id.startsWith(sessionArg));
|
const matches = sessions.filter((s) => s.id.startsWith(sessionArg));
|
||||||
|
|
||||||
if (matches.length >= 1) {
|
if (matches.length >= 1) {
|
||||||
|
|
@ -79,12 +79,12 @@ function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string
|
||||||
return sessionArg;
|
return sessionArg;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createSessionManager(parsed: Args, cwd: string): SessionManager | undefined {
|
async function createSessionManager(parsed: Args, cwd: string): Promise<SessionManager | undefined> {
|
||||||
if (parsed.noSession) {
|
if (parsed.noSession) {
|
||||||
return SessionManager.inMemory();
|
return SessionManager.inMemory();
|
||||||
}
|
}
|
||||||
if (parsed.session) {
|
if (parsed.session) {
|
||||||
const resolvedPath = resolveSessionPath(parsed.session, cwd, parsed.sessionDir);
|
const resolvedPath = await resolveSessionPath(parsed.session, cwd, parsed.sessionDir);
|
||||||
return SessionManager.open(resolvedPath, parsed.sessionDir);
|
return SessionManager.open(resolvedPath, parsed.sessionDir);
|
||||||
}
|
}
|
||||||
if (parsed.continue) {
|
if (parsed.continue) {
|
||||||
|
|
@ -309,7 +309,7 @@ export async function main(args: string[]) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create session manager based on CLI flags
|
// Create session manager based on CLI flags
|
||||||
let sessionManager = createSessionManager(parsed, cwd);
|
let sessionManager = await createSessionManager(parsed, cwd);
|
||||||
time("createSessionManager");
|
time("createSessionManager");
|
||||||
|
|
||||||
// Handle --resume: show session picker
|
// Handle --resume: show session picker
|
||||||
|
|
@ -317,14 +317,10 @@ export async function main(args: string[]) {
|
||||||
// Initialize keybindings so session picker respects user config
|
// Initialize keybindings so session picker respects user config
|
||||||
KeybindingsManager.create();
|
KeybindingsManager.create();
|
||||||
|
|
||||||
const currentSessions = SessionManager.list(cwd, parsed.sessionDir);
|
const selectedPath = await selectSession(
|
||||||
const allSessions = SessionManager.listAll();
|
(onProgress) => SessionManager.list(cwd, parsed.sessionDir, onProgress),
|
||||||
time("SessionManager.list");
|
SessionManager.listAll,
|
||||||
if (currentSessions.length === 0 && allSessions.length === 0) {
|
);
|
||||||
console.log(chalk.dim("No sessions found"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const selectedPath = await selectSession(currentSessions, allSessions);
|
|
||||||
time("selectSession");
|
time("selectSession");
|
||||||
if (!selectedPath) {
|
if (!selectedPath) {
|
||||||
console.log(chalk.dim("No session selected"));
|
console.log(chalk.dim("No session selected"));
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import {
|
||||||
truncateToWidth,
|
truncateToWidth,
|
||||||
visibleWidth,
|
visibleWidth,
|
||||||
} from "@mariozechner/pi-tui";
|
} from "@mariozechner/pi-tui";
|
||||||
import type { SessionInfo } from "../../../core/session-manager.js";
|
import type { SessionInfo, SessionListProgress } from "../../../core/session-manager.js";
|
||||||
import { theme } from "../theme/theme.js";
|
import { theme } from "../theme/theme.js";
|
||||||
import { DynamicBorder } from "./dynamic-border.js";
|
import { DynamicBorder } from "./dynamic-border.js";
|
||||||
|
|
||||||
|
|
@ -42,6 +42,8 @@ function formatSessionDate(date: Date): string {
|
||||||
|
|
||||||
class SessionSelectorHeader implements Component {
|
class SessionSelectorHeader implements Component {
|
||||||
private scope: SessionScope;
|
private scope: SessionScope;
|
||||||
|
private loading = false;
|
||||||
|
private loadProgress: { loaded: number; total: number } | null = null;
|
||||||
|
|
||||||
constructor(scope: SessionScope) {
|
constructor(scope: SessionScope) {
|
||||||
this.scope = scope;
|
this.scope = scope;
|
||||||
|
|
@ -51,20 +53,38 @@ class SessionSelectorHeader implements Component {
|
||||||
this.scope = scope;
|
this.scope = scope;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setLoading(loading: boolean): void {
|
||||||
|
this.loading = loading;
|
||||||
|
if (!loading) {
|
||||||
|
this.loadProgress = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setProgress(loaded: number, total: number): void {
|
||||||
|
this.loadProgress = { loaded, total };
|
||||||
|
}
|
||||||
|
|
||||||
invalidate(): void {}
|
invalidate(): void {}
|
||||||
|
|
||||||
render(width: number): string[] {
|
render(width: number): string[] {
|
||||||
const title = this.scope === "current" ? "Resume Session (Current Folder)" : "Resume Session (All)";
|
const title = this.scope === "current" ? "Resume Session (Current Folder)" : "Resume Session (All)";
|
||||||
const leftText = theme.bold(title);
|
const leftText = theme.bold(title);
|
||||||
const scopeText =
|
let scopeText: string;
|
||||||
|
if (this.loading) {
|
||||||
|
const progressText = this.loadProgress ? `${this.loadProgress.loaded}/${this.loadProgress.total}` : "...";
|
||||||
|
scopeText = `${theme.fg("muted", "○ Current Folder | ")}${theme.fg("accent", `Loading ${progressText}`)}`;
|
||||||
|
} else {
|
||||||
|
scopeText =
|
||||||
this.scope === "current"
|
this.scope === "current"
|
||||||
? `${theme.fg("accent", "◉ Current Folder")}${theme.fg("muted", " | ○ All")}`
|
? `${theme.fg("accent", "◉ Current Folder")}${theme.fg("muted", " | ○ All")}`
|
||||||
: `${theme.fg("muted", "○ Current Folder | ")}${theme.fg("accent", "◉ All")}`;
|
: `${theme.fg("muted", "○ Current Folder | ")}${theme.fg("accent", "◉ All")}`;
|
||||||
|
}
|
||||||
const rightText = truncateToWidth(scopeText, width, "");
|
const rightText = truncateToWidth(scopeText, width, "");
|
||||||
const availableLeft = Math.max(0, width - visibleWidth(rightText) - 1);
|
const availableLeft = Math.max(0, width - visibleWidth(rightText) - 1);
|
||||||
const left = truncateToWidth(leftText, availableLeft, "");
|
const left = truncateToWidth(leftText, availableLeft, "");
|
||||||
const spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText));
|
const spacing = Math.max(0, width - visibleWidth(left) - visibleWidth(rightText));
|
||||||
return [`${left}${" ".repeat(spacing)}${rightText}`];
|
const hint = theme.fg("muted", "Tab to toggle scope");
|
||||||
|
return [`${left}${" ".repeat(spacing)}${rightText}`, hint];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -212,6 +232,8 @@ class SessionList implements Component {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SessionsLoader = (onProgress?: SessionListProgress) => Promise<SessionInfo[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Component that renders a session selector
|
* Component that renders a session selector
|
||||||
*/
|
*/
|
||||||
|
|
@ -219,19 +241,26 @@ export class SessionSelectorComponent extends Container {
|
||||||
private sessionList: SessionList;
|
private sessionList: SessionList;
|
||||||
private header: SessionSelectorHeader;
|
private header: SessionSelectorHeader;
|
||||||
private scope: SessionScope = "current";
|
private scope: SessionScope = "current";
|
||||||
private currentSessions: SessionInfo[];
|
private currentSessions: SessionInfo[] | null = null;
|
||||||
private allSessions: SessionInfo[];
|
private allSessions: SessionInfo[] | null = null;
|
||||||
|
private currentSessionsLoader: SessionsLoader;
|
||||||
|
private allSessionsLoader: SessionsLoader;
|
||||||
|
private onCancel: () => void;
|
||||||
|
private requestRender: () => void;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
currentSessions: SessionInfo[],
|
currentSessionsLoader: SessionsLoader,
|
||||||
allSessions: SessionInfo[],
|
allSessionsLoader: SessionsLoader,
|
||||||
onSelect: (sessionPath: string) => void,
|
onSelect: (sessionPath: string) => void,
|
||||||
onCancel: () => void,
|
onCancel: () => void,
|
||||||
onExit: () => void,
|
onExit: () => void,
|
||||||
|
requestRender: () => void,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
this.currentSessions = currentSessions;
|
this.currentSessionsLoader = currentSessionsLoader;
|
||||||
this.allSessions = allSessions;
|
this.allSessionsLoader = allSessionsLoader;
|
||||||
|
this.onCancel = onCancel;
|
||||||
|
this.requestRender = requestRender;
|
||||||
this.header = new SessionSelectorHeader(this.scope);
|
this.header = new SessionSelectorHeader(this.scope);
|
||||||
|
|
||||||
// Add header
|
// Add header
|
||||||
|
|
@ -241,8 +270,8 @@ export class SessionSelectorComponent extends Container {
|
||||||
this.addChild(new DynamicBorder());
|
this.addChild(new DynamicBorder());
|
||||||
this.addChild(new Spacer(1));
|
this.addChild(new Spacer(1));
|
||||||
|
|
||||||
// Create session list
|
// Create session list (starts empty, will be populated after load)
|
||||||
this.sessionList = new SessionList(this.currentSessions, this.scope === "all");
|
this.sessionList = new SessionList([], false);
|
||||||
this.sessionList.onSelect = onSelect;
|
this.sessionList.onSelect = onSelect;
|
||||||
this.sessionList.onCancel = onCancel;
|
this.sessionList.onCancel = onCancel;
|
||||||
this.sessionList.onExit = onExit;
|
this.sessionList.onExit = onExit;
|
||||||
|
|
@ -254,18 +283,63 @@ export class SessionSelectorComponent extends Container {
|
||||||
this.addChild(new Spacer(1));
|
this.addChild(new Spacer(1));
|
||||||
this.addChild(new DynamicBorder());
|
this.addChild(new DynamicBorder());
|
||||||
|
|
||||||
// Auto-cancel if no sessions
|
// Start loading current sessions immediately
|
||||||
if (currentSessions.length === 0 && allSessions.length === 0) {
|
this.loadCurrentSessions();
|
||||||
setTimeout(() => onCancel(), 100);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private loadCurrentSessions(): void {
|
||||||
|
this.header.setLoading(true);
|
||||||
|
this.requestRender();
|
||||||
|
this.currentSessionsLoader((loaded, total) => {
|
||||||
|
this.header.setProgress(loaded, total);
|
||||||
|
this.requestRender();
|
||||||
|
}).then((sessions) => {
|
||||||
|
this.currentSessions = sessions;
|
||||||
|
this.header.setLoading(false);
|
||||||
|
this.sessionList.setSessions(sessions, false);
|
||||||
|
this.requestRender();
|
||||||
|
// If no sessions found, cancel
|
||||||
|
if (sessions.length === 0) {
|
||||||
|
this.onCancel();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private toggleScope(): void {
|
private toggleScope(): void {
|
||||||
this.scope = this.scope === "current" ? "all" : "current";
|
if (this.scope === "current") {
|
||||||
const sessions = this.scope === "current" ? this.currentSessions : this.allSessions;
|
// Switching to "all" - load if not already loaded
|
||||||
this.sessionList.setSessions(sessions, this.scope === "all");
|
if (this.allSessions === null) {
|
||||||
|
this.header.setLoading(true);
|
||||||
|
this.header.setScope("all");
|
||||||
|
this.sessionList.setSessions([], true); // Clear list while loading
|
||||||
|
this.requestRender();
|
||||||
|
// Load asynchronously with progress updates
|
||||||
|
this.allSessionsLoader((loaded, total) => {
|
||||||
|
this.header.setProgress(loaded, total);
|
||||||
|
this.requestRender();
|
||||||
|
}).then((sessions) => {
|
||||||
|
this.allSessions = sessions;
|
||||||
|
this.header.setLoading(false);
|
||||||
|
this.scope = "all";
|
||||||
|
this.sessionList.setSessions(this.allSessions, true);
|
||||||
|
this.requestRender();
|
||||||
|
// If no sessions in All scope either, cancel
|
||||||
|
if (this.allSessions.length === 0 && (this.currentSessions?.length ?? 0) === 0) {
|
||||||
|
this.onCancel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.scope = "all";
|
||||||
|
this.sessionList.setSessions(this.allSessions, true);
|
||||||
this.header.setScope(this.scope);
|
this.header.setScope(this.scope);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// Switching back to "current"
|
||||||
|
this.scope = "current";
|
||||||
|
this.sessionList.setSessions(this.currentSessions ?? [], false);
|
||||||
|
this.header.setScope(this.scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
getSessionList(): SessionList {
|
getSessionList(): SessionList {
|
||||||
return this.sessionList;
|
return this.sessionList;
|
||||||
|
|
|
||||||
|
|
@ -2876,11 +2876,10 @@ export class InteractiveMode {
|
||||||
|
|
||||||
private showSessionSelector(): void {
|
private showSessionSelector(): void {
|
||||||
this.showSelector((done) => {
|
this.showSelector((done) => {
|
||||||
const currentSessions = SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir());
|
|
||||||
const allSessions = SessionManager.listAll();
|
|
||||||
const selector = new SessionSelectorComponent(
|
const selector = new SessionSelectorComponent(
|
||||||
currentSessions,
|
(onProgress) =>
|
||||||
allSessions,
|
SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress),
|
||||||
|
SessionManager.listAll,
|
||||||
async (sessionPath) => {
|
async (sessionPath) => {
|
||||||
done();
|
done();
|
||||||
await this.handleResumeSession(sessionPath);
|
await this.handleResumeSession(sessionPath);
|
||||||
|
|
@ -2892,6 +2891,7 @@ export class InteractiveMode {
|
||||||
() => {
|
() => {
|
||||||
void this.shutdown();
|
void this.shutdown();
|
||||||
},
|
},
|
||||||
|
() => this.ui.requestRender(),
|
||||||
);
|
);
|
||||||
return { component: selector, focus: selector.getSessionList() };
|
return { component: selector, focus: selector.getSessionList() };
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue