Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

reject invalid resume session ids (#479)

ktb0a77adeb9f7
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 25752c349c..b51ceff8c0 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Fixed invalid `--resume` session IDs being submitted as prompts, with nearest-session guidance instead ([ENG-4722](https://linear.app/primeintellect/issue/ENG-4722/prime-agent-resume-accepts-incorrect-session-ids)).
- Changed `/model` to show all public models with authenticated providers first and open provider authentication when an unavailable model is selected ([ENG-4575](https://linear.app/primeintellect/issue/ENG-4575/show-all-models-in-model-and-prompt-auth-on-selection)).
- Changed the shared configuration menu to cycle tabs with Tab, use Shift+Tab for model scope, show an Escape close hint, preserve arrow-key search editing, and remove the model selector's provider shortcut.
- Fixed searchable selectors retaining their previous scroll position after the query changed.
diff --git a/packages/coding-agent/docs/sessions.md b/packages/coding-agent/docs/sessions.md
index f5c3f2b2a0..8ded8104ea 100644
--- a/packages/coding-agent/docs/sessions.md
+++ b/packages/coding-agent/docs/sessions.md
@@ -37,6 +37,8 @@ For the JSONL file format and SessionManager API, see [Session Format](session-f
`/resume` opens an interactive session picker for the current project. `pi -r` opens the same picker at startup, and `pi -r <path|id>` resumes a specific session.
+An invalid ID exits with the closest unambiguous session ID when one is available. To open the picker and send an initial prompt after selecting a session, separate the prompt with `--`: `pi -r -- "continue this work"`.
+
In the picker you can:
- search by typing
diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.ts
index a9499f56c2..12915027e8 100644
--- a/packages/coding-agent/src/cli/args.ts
+++ b/packages/coding-agent/src/cli/args.ts
@@ -17,7 +17,6 @@ export interface Args {
thinking?: ThinkingLevel;
continue?: boolean;
resume?: true | string;
- resumeSelectorFallback?: string;
help?: boolean;
version?: boolean;
mode?: Mode;
@@ -115,7 +114,6 @@ export function parseArgs(args: string[]): Args {
i++;
} else {
result.resume = next;
- result.resumeSelectorFallback = next;
i++;
}
} else {
@@ -127,7 +125,6 @@ export function parseArgs(args: string[]): Args {
result.resume = true;
} else {
result.resume = value;
- result.resumeSelectorFallback = value;
}
} else if (arg === "--provider" && i + 1 < args.length) {
result.provider = args[++i];
diff --git a/packages/coding-agent/src/cli/session-resolver.ts b/packages/coding-agent/src/cli/session-resolver.ts
new file mode 100644
index 0000000000..fcfc209152
--- /dev/null
+++ b/packages/coding-agent/src/cli/session-resolver.ts
@@ -0,0 +1 @@
+export * from "../core/session-resolver.js";
diff --git a/packages/coding-agent/src/core/session-id.ts b/packages/coding-agent/src/core/session-id.ts
new file mode 100644
index 0000000000..fda928578f
--- /dev/null
+++ b/packages/coding-agent/src/core/session-id.ts
@@ -0,0 +1,34 @@
+const DISPLAY_ID_LENGTH = 12;
+const HEX_ID_PATTERN = /^[0-9a-f]+$/;
+
+export function formatSessionDisplayId(id: string): string {
+ const normalized = normalizeHexSessionId(id);
+ if (!normalized) {
+ return id.length > DISPLAY_ID_LENGTH ? id.slice(-DISPLAY_ID_LENGTH) : id;
+ }
+ return normalized.length > DISPLAY_ID_LENGTH ? normalized.slice(-DISPLAY_ID_LENGTH) : normalized;
+}
+
+export function matchesSessionIdSuffix(candidate: string, suffix: string): boolean {
+ const normalizedCandidate = normalizeHexSessionId(candidate);
+ const normalizedSuffix = normalizeHexSessionId(suffix);
+ return !!normalizedCandidate && !!normalizedSuffix && normalizedCandidate.endsWith(normalizedSuffix);
+}
+
+export function matchesSavedSessionSelector(candidate: string, selector: string): boolean {
+ const normalizedCandidate = normalizeHexSessionId(candidate);
+ const normalizedSelector = normalizeHexSessionId(selector);
+ if (normalizedCandidate && normalizedSelector) {
+ return normalizedCandidate.startsWith(normalizedSelector) || normalizedCandidate.endsWith(normalizedSelector);
+ }
+ return candidate.startsWith(selector);
+}
+
+export function normalizeSessionId(id: string): string {
+ return id.replaceAll("-", "").toLowerCase();
+}
+
+function normalizeHexSessionId(id: string): string | undefined {
+ const normalized = normalizeSessionId(id);
+ return normalized && HEX_ID_PATTERN.test(normalized) ? normalized : undefined;
+}
diff --git a/packages/coding-agent/src/core/session-resolver.ts b/packages/coding-agent/src/core/session-resolver.ts
new file mode 100644
index 0000000000..0e8a7ac2eb
--- /dev/null
+++ b/packages/coding-agent/src/core/session-resolver.ts
@@ -0,0 +1,147 @@
+import { matchesSavedSessionSelector, normalizeSessionId } from "./session-id.js";
+import type { SessionInfo } from "./session-manager.js";
+import { SessionManager } from "./session-manager.js";
+
+export type ResolvedSession =
+ | { type: "path"; path: string }
+ | { type: "local"; path: string }
+ | { type: "global"; path: string; cwd: string };
+
+export class SessionSelectorError extends Error {
+ constructor(
+ message: string,
+ readonly selector: string,
+ ) {
+ super(message);
+ this.name = "SessionSelectorError";
+ }
+}
+
+export class SessionSelectorNotFoundError extends SessionSelectorError {
+ constructor(
+ selector: string,
+ readonly suggestion?: string,
+ ) {
+ super(`No session found matching '${selector}'`, selector);
+ this.name = "SessionSelectorNotFoundError";
+ }
+}
+
+export class SessionSelectorAmbiguousError extends SessionSelectorError {
+ constructor(
+ selector: string,
+ readonly matches: readonly SessionInfo[],
+ ) {
+ super(
+ `Ambiguous saved session "${selector}": matches ${matches
+ .map((session) => `${session.id}${session.name ? ` (${session.name})` : ""}`)
+ .join(", ")}`,
+ selector,
+ );
+ this.name = "SessionSelectorAmbiguousError";
+ }
+}
+
+export function looksLikeSessionPath(selector: string): boolean {
+ return selector.includes("/") || selector.includes("\\") || selector.endsWith(".jsonl");
+}
+
+export async function resolveSessionPath(selector: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {
+ if (looksLikeSessionPath(selector)) {
+ return { type: "path", path: selector };
+ }
+
+ const localSessions = await SessionManager.list(cwd, sessionDir);
+ const localExactMatch = resolveExactMatch(selector, localSessions);
+ if (localExactMatch) {
+ return { type: "local", path: localExactMatch.path };
+ }
+
+ const allSessions = await SessionManager.listAll(undefined, sessionDir);
+ const globalExactMatch = resolveExactMatch(selector, allSessions);
+ if (globalExactMatch) {
+ return { type: "global", path: globalExactMatch.path, cwd: globalExactMatch.cwd };
+ }
+
+ const localMatch = resolvePartialMatch(selector, localSessions);
+ if (localMatch) {
+ return { type: "local", path: localMatch.path };
+ }
+
+ const globalMatch = resolvePartialMatch(selector, allSessions);
+ if (globalMatch) {
+ return { type: "global", path: globalMatch.path, cwd: globalMatch.cwd };
+ }
+
+ throw new SessionSelectorNotFoundError(selector, findClosestSessionId(selector, [...localSessions, ...allSessions]));
+}
+
+export function findClosestSessionId(
+ selector: string,
+ sessions: readonly Pick<SessionInfo, "id">[],
+): string | undefined {
+ const normalizedSelector = normalizeSessionId(selector);
+ if (normalizedSelector.length < 4) {
+ return undefined;
+ }
+
+ const uniqueIds = [...new Set(sessions.map((session) => session.id))];
+ let closest: { id: string; distance: number } | undefined;
+ let tied = false;
+
+ for (const id of uniqueIds) {
+ const normalizedId = normalizeSessionId(id);
+ const length = Math.min(normalizedSelector.length, normalizedId.length);
+ const distance = Math.min(
+ editDistance(normalizedSelector, normalizedId.slice(0, length)),
+ editDistance(normalizedSelector, normalizedId.slice(-length)),
+ );
+ if (!closest || distance < closest.distance) {
+ closest = { id, distance };
+ tied = false;
+ } else if (distance === closest.distance) {
+ tied = true;
+ }
+ }
+
+ const maximumDistance = Math.max(1, Math.floor(normalizedSelector.length / 5));
+ return closest && !tied && closest.distance <= maximumDistance ? closest.id : undefined;
+}
+
+function resolveExactMatch(selector: string, sessions: readonly SessionInfo[]): SessionInfo | undefined {
+ const normalizedSelector = normalizeSessionId(selector);
+ return resolveUniqueMatch(
+ selector,
+ sessions.filter((session) => normalizeSessionId(session.id) === normalizedSelector),
+ );
+}
+
+function resolvePartialMatch(selector: string, sessions: readonly SessionInfo[]): SessionInfo | undefined {
+ const matches = sessions.filter((session) => matchesSavedSessionSelector(session.id, selector));
+ return resolveUniqueMatch(selector, matches);
+}
+
+function resolveUniqueMatch(selector: string, matches: readonly SessionInfo[]): SessionInfo | undefined {
+ if (matches.length > 1) {
+ throw new SessionSelectorAmbiguousError(selector, matches);
+ }
+ return matches[0];
+}
+
+function editDistance(left: string, right: string): number {
+ const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
+ for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
+ let diagonal = previous[0]!;
+ previous[0] = leftIndex;
+ for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
+ const above = previous[rightIndex]!;
+ previous[rightIndex] = Math.min(
+ previous[rightIndex]! + 1,
+ previous[rightIndex - 1]! + 1,
+ diagonal + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
+ );
+ diagonal = above;
+ }
+ }
+ return previous[right.length]!;
+}
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index ea7319f7c3..76b7f4de74 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -28,7 +28,13 @@ import { listModels } from "./cli/list-models.js";
import { installOwnedSessionRecoveryTracking, isOwnedSessionWorkerProcess } from "./cli/owned-session-worker.js";
import { handlePublicCommand } from "./cli/public-command.js";
import { selectSession } from "./cli/session-picker.js";
-import { expandTildePath, getAgentDir, getSessionDirEnvOverride, VERSION } from "./config.js";
+import {
+ looksLikeSessionPath,
+ resolveSessionPath,
+ SessionSelectorError,
+ SessionSelectorNotFoundError,
+} from "./cli/session-resolver.js";
+import { APP_NAME, expandTildePath, getAgentDir, getSessionDirEnvOverride, VERSION } from "./config.js";
import {
type AgentSessionRuntimeConfig,
mergeAgentSessionRuntimeConfig,
@@ -300,10 +306,6 @@ export async function findActiveDaemonSessionSummaryForInteractiveStartup(
}
}
-function looksLikeSessionPath(sessionArg: string): boolean {
- return sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl");
-}
-
async function prepareInitialMessage(
parsed: Args,
autoResizeImages: boolean,
@@ -325,44 +327,6 @@ async function prepareInitialMessage(
});
}
-/** Result from resolving a session argument */
-type ResolvedSession =
- | { type: "path"; path: string } // Direct file path
- | { type: "local"; path: string } // Found in current project
- | { type: "global"; path: string; cwd: string } // Found in different project
- | { type: "not_found"; arg: string }; // Not found anywhere
-
-/**
- * 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.
- */
-async function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {
- // If it looks like a file path, use as-is
- if (looksLikeSessionPath(sessionArg)) {
- return { type: "path", path: sessionArg };
- }
-
- // Try to match as session ID in current project first
- const localSessions = await SessionManager.list(cwd, sessionDir);
- const localMatches = localSessions.filter((s) => s.id.startsWith(sessionArg));
-
- if (localMatches.length >= 1) {
- return { type: "local", path: localMatches[0].path };
- }
-
- // Try global search across all projects
- const allSessions = await SessionManager.listAll();
- const globalMatches = allSessions.filter((s) => s.id.startsWith(sessionArg));
-
- if (globalMatches.length >= 1) {
- const match = globalMatches[0];
- return { type: "global", path: match.path, cwd: match.cwd };
- }
-
- // Not found anywhere
- return { type: "not_found", arg: sessionArg };
-}
-
/** Prompt user for yes/no confirmation */
async function promptConfirm(message: string): Promise<boolean> {
return new Promise((resolve) => {
@@ -471,14 +435,6 @@ function getResumeSelector(parsed: Pick<Args, "resume">): string | undefined {
return typeof parsed.resume === "string" ? parsed.resume : undefined;
}
-export function restoreResumeSelectorFallback(parsed: Args, selector: string): boolean {
- if (parsed.resumeSelectorFallback !== selector) return false;
- delete parsed.resume;
- delete parsed.resumeSelectorFallback;
- parsed.messages.unshift(selector);
- return true;
-}
-
export async function createSessionManager(
parsed: Args,
cwd: string,
@@ -499,11 +455,6 @@ export async function createSessionManager(
case "local":
case "global":
return forkSessionOrExit(resolved.path, cwd, sessionDir);
-
- case "not_found":
- if (restoreResumeSelectorFallback(parsed, resolved.arg)) break;
- console.error(chalk.red(`No session found matching '${resolved.arg}'`));
- process.exit(1);
}
}
@@ -525,11 +476,6 @@ export async function createSessionManager(
}
return forkSessionOrExit(resolved.path, cwd, sessionDir);
}
-
- case "not_found":
- if (restoreResumeSelectorFallback(parsed, resolved.arg)) break;
- console.error(chalk.red(`No session found matching '${resolved.arg}'`));
- process.exit(1);
}
}
@@ -1252,7 +1198,20 @@ export async function main(args: string[], options?: MainOptions) {
) {
sessionManager = SessionManager.inMemory(cwd);
} else {
- sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);
+ try {
+ sessionManager = await createSessionManager(parsed, cwd, sessionDir, startupSettingsManager);
+ } catch (error) {
+ if (!(error instanceof SessionSelectorError)) {
+ throw error;
+ }
+ const suggestion =
+ error instanceof SessionSelectorNotFoundError && error.suggestion
+ ? ` Did you mean '${error.suggestion}'?`
+ : "";
+ console.error(chalk.red(`Error: ${error.message}.${suggestion}`));
+ console.error(chalk.dim(`Run "${APP_NAME} --resume" to browse sessions.`));
+ process.exit(1);
+ }
}
const missingSessionCwdIssue = getMissingSessionCwdIssue(sessionManager, cwd);
if (missingSessionCwdIssue) {
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 6858595f9c..a5b3802fe8 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -98,6 +98,7 @@ import type {
import { deleteSessionFile } from "../../core/session-file-actions.js";
import { acquireSessionLease, type SessionLease } from "../../core/session-lease.js";
import { readSessionInfo, type SessionInfo, SessionManager } from "../../core/session-manager.js";
+import { resolveSessionPath } from "../../core/session-resolver.js";
import type { SessionStats } from "../../core/session-stats.js";
import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";
import { killTrackedDetachedChildren } from "../../utils/shell.js";
@@ -5166,43 +5167,5 @@ export function shouldSendDaemonOutboundToClient(client: DaemonSocketClient, mes
}
export async function resolveDaemonSessionPath(selector: string, cwd: string, sessionDir?: string): Promise<string> {
- if (looksLikeSessionPath(selector)) {
- return selector;
- }
-
- const localMatches = (await SessionManager.list(cwd, sessionDir)).filter((session) =>
- session.id.startsWith(selector),
- );
- const localMatch = resolveUniqueSavedSessionMatch(selector, localMatches);
- if (localMatch) {
- return localMatch.path;
- }
-
- const allSessions =
- sessionDir !== undefined ? await SessionManager.listAll(undefined, sessionDir) : await SessionManager.listAll();
- const globalMatches = allSessions.filter((session) => session.id.startsWith(selector));
- const globalMatch = resolveUniqueSavedSessionMatch(selector, globalMatches);
- if (globalMatch) {
- return globalMatch.path;
- }
-
- throw new Error(`No session found matching "${selector}"`);
-}
-
-function resolveUniqueSavedSessionMatch(selector: string, matches: readonly SessionInfo[]): SessionInfo | undefined {
- if (matches.length === 0) {
- return undefined;
- }
- if (matches.length > 1) {
- throw new Error(
- `Ambiguous saved session "${selector}": matches ${matches
- .map((session) => `${session.id}${session.name ? ` (${session.name})` : ""}`)
- .join(", ")}`,
- );
- }
- return matches[0];
-}
-
-function looksLikeSessionPath(selector: string): boolean {
- return selector.includes("/") || selector.includes("\\") || selector.endsWith(".jsonl");
+ return (await resolveSessionPath(selector, cwd, sessionDir)).path;
}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-id.ts b/packages/coding-agent/src/modes/daemon/daemon-session-id.ts
index ed7956b107..6faa564c12 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-id.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-id.ts
@@ -1,21 +1 @@
-const DISPLAY_ID_LENGTH = 12;
-const HEX_ID_PATTERN = /^[0-9a-f]+$/;
-
-export function formatSessionDisplayId(id: string): string {
- const normalized = normalizeSessionId(id);
- if (!normalized) {
- return id.length > DISPLAY_ID_LENGTH ? id.slice(-DISPLAY_ID_LENGTH) : id;
- }
- return normalized.length > DISPLAY_ID_LENGTH ? normalized.slice(-DISPLAY_ID_LENGTH) : normalized;
-}
-
-export function matchesSessionIdSuffix(candidate: string, suffix: string): boolean {
- const normalizedCandidate = normalizeSessionId(candidate);
- const normalizedSuffix = normalizeSessionId(suffix);
- return !!normalizedCandidate && !!normalizedSuffix && normalizedCandidate.endsWith(normalizedSuffix);
-}
-
-function normalizeSessionId(id: string): string | undefined {
- const normalized = id.replaceAll("-", "").toLowerCase();
- return normalized && HEX_ID_PATTERN.test(normalized) ? normalized : undefined;
-}
+export { formatSessionDisplayId, matchesSessionIdSuffix } from "../../core/session-id.js";
diff --git a/packages/coding-agent/test/args.test.ts b/packages/coding-agent/test/args.test.ts
index 2be760a8d0..e2899f0bb3 100644
--- a/packages/coding-agent/test/args.test.ts
+++ b/packages/coding-agent/test/args.test.ts
@@ -104,31 +104,33 @@ describe("parseArgs", () => {
const sessionPath = "C:\\Users\\me\\session.jsonl";
const result = parseArgs(["--resume", sessionPath]);
expect(result.resume).toBe(sessionPath);
- expect(result.resumeSelectorFallback).toBe(sessionPath);
expect(result.messages).toEqual([]);
});
test("parses --resume with a slash-containing relative session path", () => {
const result = parseArgs(["--resume", "sessions/current"]);
expect(result.resume).toBe("sessions/current");
- expect(result.resumeSelectorFallback).toBe("sessions/current");
expect(result.messages).toEqual([]);
});
- test("records text after --resume as a selector candidate with message fallback", () => {
+ test("treats the value after --resume as an authoritative selector", () => {
const result = parseArgs(["--resume", "fix", "the", "bug"]);
expect(result.resume).toBe("fix");
- expect(result.resumeSelectorFallback).toBe("fix");
expect(result.messages).toEqual(["the", "bug"]);
});
- test("records text after --resume= as a selector candidate with message fallback", () => {
+ test("treats the value after --resume= as an authoritative selector", () => {
const result = parseArgs(["--resume=fix"]);
expect(result.resume).toBe("fix");
- expect(result.resumeSelectorFallback).toBe("fix");
expect(result.messages).toEqual([]);
});
+ test("supports an initial prompt after the bare resume picker", () => {
+ const result = parseArgs(["--resume", "--", "continue", "the", "session"]);
+ expect(result.resume).toBe(true);
+ expect(result.messages).toEqual(["continue", "the", "session"]);
+ });
+
test("treats empty --resume values as the bare resume picker flag", () => {
const separated = parseArgs(["--resume", ""]);
expect(separated.resume).toBe(true);
diff --git a/packages/coding-agent/test/daemon-session-id.test.ts b/packages/coding-agent/test/daemon-session-id.test.ts
index b09cb069de..3b812ea068 100644
--- a/packages/coding-agent/test/daemon-session-id.test.ts
+++ b/packages/coding-agent/test/daemon-session-id.test.ts
@@ -78,6 +78,51 @@ describe("resolveDaemonSessionPath", () => {
rmSync(tempDir, { recursive: true, force: true });
}
});
+
+ it("resolves the normalized suffix shown by the session list", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-session-id-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ const sessionId = "019e71ec-e08a-75a9-b573-aaaaaaaaaaaa";
+ const sessionPath = createSavedSession(cwd, sessionDir, sessionId);
+
+ await expect(resolveDaemonSessionPath("AAAAAA-AAAAAA", cwd, sessionDir)).resolves.toBe(sessionPath);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("raises when a saved session suffix matches multiple sessions", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-session-id-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ createSavedSession(cwd, sessionDir, "019e71ec-e08a-75a9-b573-aaaaaaaaaaaa");
+ createSavedSession(cwd, sessionDir, "029e71ec-e08a-75a9-b573-aaaaaaaaaaaa");
+
+ await expect(resolveDaemonSessionPath("aaaaaaaaaaaa", cwd, sessionDir)).rejects.toThrow(
+ /Ambiguous saved session "aaaaaaaaaaaa"/,
+ );
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("prefers an exact normalized ID over prefix and suffix matches", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-session-id-"));
+ try {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ const exactPath = createSavedSession(cwd, sessionDir, "abcd");
+ createSavedSession(cwd, sessionDir, "abcd1");
+ createSavedSession(cwd, sessionDir, "1abcd");
+
+ await expect(resolveDaemonSessionPath("AB-CD", cwd, sessionDir)).resolves.toBe(exactPath);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
});
function makeSessionMap(states: ActiveSessionState[]): Map<string, ActiveSessionState> {
@@ -97,8 +142,9 @@ function makeState(activeSessionId: string, sessionId: string): ActiveSessionSta
} as unknown as ActiveSessionState;
}
-function createSavedSession(cwd: string, sessionDir: string, sessionId: string): void {
+function createSavedSession(cwd: string, sessionDir: string, sessionId: string): string {
const session = SessionManager.create(cwd, sessionDir);
session.newSession({ id: sessionId });
session.appendSessionState({ status: "archived" });
+ return session.getSessionFile()!;
}
diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.ts
index 577c750ba8..c1bf12f6b0 100644
--- a/packages/coding-agent/test/main-interactive-routing.test.ts
+++ b/packages/coding-agent/test/main-interactive-routing.test.ts
@@ -11,7 +11,6 @@ import {
type InteractiveDaemonStartupDecision,
parseAgentsViewCommand,
resolveRuntimeSessionOptions,
- restoreResumeSelectorFallback,
shouldEnsureDaemonBeforeActiveSessionLookup,
shouldEnsureInteractiveDaemonForStartup,
shouldOpenAgentsViewForDaemonInteractive,
@@ -264,22 +263,6 @@ describe("daemon-backed interactive session manager routing", () => {
expect(shouldUseEphemeralSessionManagerForDaemonInteractive(decision)).toBe(false);
});
- test("restores an unresolved resume selector candidate as prompt text", () => {
- const parsed = {
- resume: "fix",
- resumeSelectorFallback: "fix",
- messages: ["the", "bug"],
- fileArgs: [],
- unknownFlags: new Map(),
- diagnostics: [],
- };
-
- expect(restoreResumeSelectorFallback(parsed, "fix")).toBe(true);
- expect(parsed.resume).toBeUndefined();
- expect(parsed.resumeSelectorFallback).toBeUndefined();
- expect(parsed.messages).toEqual(["fix", "the", "bug"]);
- });
-
test("finds an active daemon session by resolved session file", () => {
const inactiveSummary = makeSessionSummary({
id: "saved-1",
diff --git a/packages/coding-agent/test/session-cwd.test.ts b/packages/coding-agent/test/session-cwd.test.ts
index b635e8f2c3..cf3583ccab 100644
--- a/packages/coding-agent/test/session-cwd.test.ts
+++ b/packages/coding-agent/test/session-cwd.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { parseArgs } from "../src/cli/args.js";
+import { SessionSelectorNotFoundError } from "../src/cli/session-resolver.js";
import { type CreateAgentSessionRuntimeFactory, createAgentSessionRuntime } from "../src/core/agent-session-runtime.js";
import { getMissingSessionCwdIssue, MissingSessionCwdError } from "../src/core/session-cwd.js";
import { SessionManager } from "../src/core/session-manager.js";
@@ -108,19 +109,23 @@ describe("session cwd handling", () => {
expect(sessionManager.getCwd()).toBe(explicitCwd);
});
- it("restores an unresolved resume selector as prompt text for a fresh session", async () => {
+ it("rejects an unresolved resume selector without converting it to prompt text", async () => {
const cwd = createTempDir("pi-session-cwd-resume-fallback");
const agentDir = createTempDir("pi-session-cwd-resume-fallback-agent-dir");
const sessionDir = createTempDir("pi-session-cwd-resume-fallback-session-dir");
cleanupPaths.push(cwd, agentDir, sessionDir);
const parsed = parseArgs(["--resume", "fix", "the", "bug"]);
- const sessionManager = await createSessionManager(parsed, cwd, sessionDir, SettingsManager.create(cwd, agentDir));
+ await expect(
+ createSessionManager(parsed, cwd, sessionDir, SettingsManager.create(cwd, agentDir)),
+ ).rejects.toMatchObject({
+ name: SessionSelectorNotFoundError.name,
+ selector: "fix",
+ suggestion: undefined,
+ });
- expect(sessionManager.getCwd()).toBe(cwd);
- expect(parsed.resume).toBeUndefined();
- expect(parsed.resumeSelectorFallback).toBeUndefined();
- expect(parsed.messages).toEqual(["fix", "the", "bug"]);
+ expect(parsed.resume).toBe("fix");
+ expect(parsed.messages).toEqual(["the", "bug"]);
});
it("throws a controlled error before runtime creation when the stored cwd is missing", async () => {
diff --git a/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts b/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts
new file mode 100644
index 0000000000..a002600ab7
--- /dev/null
+++ b/packages/coding-agent/test/suite/regressions/4722-invalid-resume-selector.test.ts
@@ -0,0 +1,107 @@
+import { join } from "node:path";
+import { fauxAssistantMessage } from "@earendil-works/pi-ai";
+import { afterEach, describe, expect, it } from "vitest";
+import { parseArgs } from "../../../src/cli/args.js";
+import {
+ findClosestSessionId,
+ SessionSelectorAmbiguousError,
+ SessionSelectorNotFoundError,
+} from "../../../src/cli/session-resolver.js";
+import { SessionManager } from "../../../src/core/session-manager.js";
+import { SettingsManager } from "../../../src/core/settings-manager.js";
+import { createSessionManager } from "../../../src/main.js";
+import { createHarness, type Harness } from "../harness.js";
+
+describe("ENG-4722 invalid resume selectors", () => {
+ let harness: Harness | undefined;
+
+ afterEach(() => {
+ harness?.cleanup();
+ harness = undefined;
+ });
+
+ it("rejects a mistyped session ID with the closest saved ID", async () => {
+ harness = await createHarness({ persistSession: true });
+ harness.setResponses([fauxAssistantMessage("saved")]);
+ await harness.session.prompt("persist this session");
+
+ const sessionId = harness.session.sessionId;
+ const lastCharacter = sessionId.at(-1)!;
+ const mistypedId = `${sessionId.slice(0, -1)}${lastCharacter === "0" ? "1" : "0"}`;
+ const parsed = parseArgs(["--resume", mistypedId, "do not submit this"]);
+ const sessionDir = join(harness.tempDir, "sessions");
+
+ await expect(
+ createSessionManager(parsed, harness.tempDir, sessionDir, SettingsManager.inMemory()),
+ ).rejects.toMatchObject({
+ name: SessionSelectorNotFoundError.name,
+ selector: mistypedId,
+ suggestion: sessionId,
+ });
+ expect(parsed.resume).toBe(mistypedId);
+ expect(parsed.messages).toEqual(["do not submit this"]);
+ });
+
+ it("does not suggest tied or low-confidence session IDs", () => {
+ expect(findClosestSessionId("abcx", [{ id: "abca1111" }, { id: "abcb2222" }])).toBeUndefined();
+ expect(findClosestSessionId("wxyz1234", [{ id: "abcdef0123456789" }])).toBeUndefined();
+ expect(findClosestSessionId("abcd", [])).toBeUndefined();
+ });
+
+ it("rejects an ambiguous saved session prefix", async () => {
+ harness = await createHarness();
+ const sessionDir = join(harness.tempDir, "sessions");
+ createSavedSession(harness.tempDir, sessionDir, "11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
+ createSavedSession(harness.tempDir, sessionDir, "11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
+ const parsed = parseArgs(["--resume", "11111111", "do not submit this"]);
+
+ await expect(
+ createSessionManager(parsed, harness.tempDir, sessionDir, SettingsManager.inMemory()),
+ ).rejects.toMatchObject({
+ name: SessionSelectorAmbiguousError.name,
+ selector: "11111111",
+ });
+ expect(parsed.messages).toEqual(["do not submit this"]);
+ });
+
+ it("accepts the normalized suffix displayed by the session list", async () => {
+ harness = await createHarness();
+ const sessionDir = join(harness.tempDir, "sessions");
+ const sessionId = "019e71ec-e08a-75a9-b573-aaaaaaaaaaaa";
+ createSavedSession(harness.tempDir, sessionDir, sessionId);
+ const parsed = parseArgs(["--resume", "aaaaaaaaaaaa"]);
+
+ const sessionManager = await createSessionManager(
+ parsed,
+ harness.tempDir,
+ sessionDir,
+ SettingsManager.inMemory(),
+ );
+
+ expect(sessionManager.getSessionId()).toBe(sessionId);
+ });
+
+ it("prefers an exact normalized ID over prefix and suffix matches", async () => {
+ harness = await createHarness();
+ const sessionDir = join(harness.tempDir, "sessions");
+ createSavedSession(harness.tempDir, sessionDir, "abcd");
+ createSavedSession(harness.tempDir, sessionDir, "abcd1");
+ createSavedSession(harness.tempDir, sessionDir, "1abcd");
+ const parsed = parseArgs(["--resume", "AB-CD"]);
+
+ const sessionManager = await createSessionManager(
+ parsed,
+ harness.tempDir,
+ sessionDir,
+ SettingsManager.inMemory(),
+ );
+
+ expect(sessionManager.getSessionId()).toBe("abcd");
+ });
+});
+
+function createSavedSession(cwd: string, sessionDir: string, sessionId: string): void {
+ const session = SessionManager.create(cwd, sessionDir);
+ session.newSession({ id: sessionId });
+ session.appendSessionState({ status: "archived" });
+}