TypeScript
fix(server): bound terminal history names for encrypted filesystems (#21654)
JesstLe32683c96f691
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.tsindex 7e925677729..61fe149cf83 100644--- a/apps/server/src/terminal/Manager.test.ts+++ b/apps/server/src/terminal/Manager.test.ts@@ -1195,7 +1195,7 @@ it.layer(it.effect("keeps reading and deleting history at an encoded path that already fit", () =>Effect.gen(function* () {- const threadId = "x".repeat(120);+ const threadId = "x".repeat(48);const { manager, logsDir } = yield* createManager();const fs = yield* FileSystem.FileSystem;const logPath = yield* historyLogPath(logsDir, threadId);@@ -1213,6 +1213,180 @@ it.layer(}),);+ it.effect.each([+ {+ label: "delegated setup",+ threadId:+ "thread:delegated-task:command%3Amcp%3A00000000-0000-4000-8000-000000000000%3Adelegate-task%3Aexample-r4-workspace-prepare-engine3",+ terminalId: "setup-setup-worktree-2",+ },+ { label: "long thread", threadId: "t".repeat(400), terminalId: DEFAULT_TERMINAL_ID },+ { label: "Unicode thread", threadId: "项目😀".repeat(60), terminalId: "setup" },+ { label: "long terminal", threadId: "short", terminalId: "t".repeat(128) },+ { label: "142-byte boundary", threadId: "t".repeat(48), terminalId: "s".repeat(48) },+ { label: "144-byte boundary", threadId: "t".repeat(49), terminalId: "s".repeat(48) },+ ])("persists $label history with a 143-byte filename limit", ({ threadId, terminalId }) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const check = (filePath: string) =>+ Buffer.byteLength(path.basename(filePath)) <= 143+ ? Effect.void+ : Effect.fail(+ PlatformError.systemError({+ _tag: "Unknown",+ module: "FileSystem",+ method: "access",+ pathOrDescriptor: filePath,+ cause: { code: "ENAMETOOLONG" },+ }),+ );+ const limited = FileSystem.FileSystem.of({+ ...fs,+ exists: (filePath) => Effect.andThen(check(filePath), fs.exists(filePath)),+ open: (filePath, options) => Effect.andThen(check(filePath), fs.open(filePath, options)),+ writeFileString: (filePath, data, options) =>+ Effect.andThen(check(filePath), fs.writeFileString(filePath, data, options)),+ remove: (filePath, options) =>+ Effect.andThen(check(filePath), fs.remove(filePath, options)),+ });+ const { manager, ptyAdapter, logsDir } = yield* createManager().pipe(+ Effect.provideService(FileSystem.FileSystem, limited),+ );+ yield* manager.open(openInput({ threadId, terminalId }));+ ptyAdapter.processes[0]!.emitData("setup output\n");+ yield* manager.close({ threadId, terminalId });+ const names = yield* fs.readDirectory(logsDir);+ expect(names).toHaveLength(1);+ expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);+ expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(+ "setup output\n",+ );+ const otherThread = `${threadId}-other`;+ expect((yield* manager.open(openInput({ threadId: otherThread, terminalId }))).history).toBe(+ "",+ );+ ptyAdapter.processes[2]!.emitData("other output\n");+ yield* manager.close({ threadId: otherThread, terminalId });+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(2);+ yield* manager.close({ threadId, terminalId, deleteHistory: true });+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);+ yield* manager.close({ threadId: otherThread, deleteHistory: true });+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);+ }),+ );++ it.effect.each([+ { source: "encoded", terminalId: DEFAULT_TERMINAL_ID },+ { source: "encoded", terminalId: "setup-setup-worktree-2" },+ { source: "sanitized", terminalId: DEFAULT_TERMINAL_ID },+ ])("migrates oversized $source history for $terminalId", ({ source, terminalId }) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const { manager, logsDir } = yield* createManager();+ const threadId = "m".repeat(100);+ const oldPath =+ source === "encoded"+ ? path.join(+ logsDir,+ `terminal_${Base64Url.encode(threadId)}${terminalId === DEFAULT_TERMINAL_ID ? "" : `_${Base64Url.encode(terminalId)}`}.log`,+ )+ : path.join(logsDir, `${threadId}.log`);+ yield* fs.writeFileString(oldPath, "old output\n");+ expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(+ "old output\n",+ );+ const names = yield* fs.readDirectory(logsDir);+ expect(names).toHaveLength(1);+ expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);+ expect(yield* fs.exists(oldPath)).toBe(false);+ expect(yield* fs.readFileString(path.join(logsDir, names[0]!))).toBe("old output\n");+ yield* manager.close({ threadId, terminalId, deleteHistory: true });+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);+ }),+ );++ it.effect.each(["terminal", "thread"] as const)(+ "deletes compact and older encoded history when closing a %s",+ (scope) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const { manager, logsDir } = yield* createManager();+ const threadId = "d".repeat(100);+ const terminalId = "setup-setup-worktree-2";+ yield* manager.open(openInput({ threadId, terminalId }));+ yield* manager.close({ threadId, terminalId });+ const oldPath = path.join(+ logsDir,+ `terminal_${Base64Url.encode(threadId)}_${Base64Url.encode(terminalId)}.log`,+ );+ yield* fs.writeFileString(oldPath, "stale copy\n");+ yield* fs.writeFileString(path.join(logsDir, "unrelated.log"), "keep\n");+ if (scope === "terminal") {+ yield* manager.close({ threadId, terminalId, deleteHistory: true });+ } else {+ yield* manager.close({ threadId, deleteHistory: true });+ }+ expect(yield* fs.readDirectory(logsDir)).toEqual(["unrelated.log"]);+ }),+ );++ it.effect("prefers bounded history over a stale encoded copy", () =>+ Effect.gen(function* () {+ const { manager, ptyAdapter, logsDir } = yield* createManager();+ const fs = yield* FileSystem.FileSystem;+ const threadId = "p".repeat(100);+ yield* manager.open(openInput({ threadId }));+ ptyAdapter.processes[0]!.emitData("current\n");+ yield* manager.close({ threadId });+ const oldPath = yield* historyLogPath(logsDir, threadId);+ yield* fs.writeFileString(oldPath, "stale\n");++ expect((yield* manager.open(openInput({ threadId }))).history).toBe("current\n");+ yield* manager.close({ threadId, terminalId: DEFAULT_TERMINAL_ID, deleteHistory: true });+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);+ }),+ );++ it.effect("retains encoded history if migration cannot write the bounded file", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ let failNextWrite = true;+ const limited = FileSystem.FileSystem.of({+ ...fs,+ writeFileString: (filePath, data, options) => {+ if (!failNextWrite) return fs.writeFileString(filePath, data, options);+ failNextWrite = false;+ return fs.writeFileString(filePath, "partial").pipe(+ Effect.andThen(+ Effect.fail(+ PlatformError.systemError({+ _tag: "Unknown",+ module: "FileSystem",+ method: "writeFileString",+ cause: { code: "ENOSPC" },+ }),+ ),+ ),+ );+ },+ });+ const { manager, logsDir } = yield* createManager().pipe(+ Effect.provideService(FileSystem.FileSystem, limited),+ );+ const threadId = "f".repeat(100);+ const oldPath = yield* historyLogPath(logsDir, threadId);+ yield* fs.writeFileString(oldPath, "preserve me\n");++ expect(Exit.isFailure(yield* Effect.exit(manager.open(openInput({ threadId }))))).toBe(true);+ expect(yield* fs.readFileString(oldPath)).toBe("preserve me\n");+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);+ expect((yield* manager.open(openInput({ threadId }))).history).toBe("preserve me\n");+ }),+ );+it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>Effect.gen(function* () {const { manager, logsDir } = yield* createManager();diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.tsindex bd7ca2c92e3..ca93558d623 100644--- a/apps/server/src/terminal/Manager.ts+++ b/apps/server/src/terminal/Manager.ts@@ -93,6 +93,8 @@ export {const DEFAULT_HISTORY_LINE_LIMIT = 5_000;const DEFAULT_HISTORY_BYTE_LIMIT = 8 * 1024 * 1024;+// eCryptfs permits 143-byte names.+const MAX_HISTORY_FILENAME_BYTES = 143;const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;const DEFAULT_PERSIST_DEBOUNCE_MS = 250;const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;@@ -1304,8 +1306,6 @@ function legacySafeThreadId(threadId: string): string {return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");}-const MAX_FILE_NAME_BYTES = 255;-function encodedHistoryThreadPart(threadId: string): string {return `terminal_${Base64Url.encode(threadId)}`;}@@ -1672,28 +1672,46 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func}});- // Nested subagent thread ids can encode past the filename limit. Only names that would not fit- // switch to hashed ids, so every history file that already exists keeps its path.- const historyPath = (threadId: string, terminalId: string) => {- const isDefault = terminalId === DEFAULT_TERMINAL_ID;- const encodedName = joinHistoryFileName(- encodedHistoryThreadPart(threadId),- isDefault ? null : Base64Url.encode(terminalId),+ const encodedHistoryPath = (threadId: string, terminalId: string) =>+ path.join(+ logsDir,+ joinHistoryFileName(+ encodedHistoryThreadPart(threadId),+ terminalId === DEFAULT_TERMINAL_ID ? null : Base64Url.encode(terminalId),+ ),);- if (encodedName.length <= MAX_FILE_NAME_BYTES) {- return path.join(logsDir, encodedName);- }++ const historyPath = (threadId: string, terminalId: string) => {+ const encoded = encodedHistoryPath(threadId, terminalId);+ if (path.basename(encoded).length <= MAX_HISTORY_FILENAME_BYTES) return encoded;return path.join(logsDir,- joinHistoryFileName(hashedHistoryThreadPart(threadId), isDefault ? null : hashId(terminalId)),+ joinHistoryFileName(+ hashedHistoryThreadPart(threadId),+ terminalId === DEFAULT_TERMINAL_ID ? null : hashId(terminalId),+ ),);};- const legacyHistoryName = (threadId: string) => `${legacySafeThreadId(threadId)}.log`;- const legacyHistoryPath = (threadId: string) => path.join(logsDir, legacyHistoryName(threadId));- // Ids this long could never have been written under the legacy name.- const hasLegacyHistoryPath = (threadId: string) =>- Buffer.byteLength(legacyHistoryName(threadId)) <= MAX_FILE_NAME_BYTES;+ const legacyHistoryPath = (threadId: string) =>+ path.join(logsDir, `${legacySafeThreadId(threadId)}.log`);++ const historyPaths = (threadId: string, terminalId: string) => [+ ...new Set([+ historyPath(threadId, terminalId),+ encodedHistoryPath(threadId, terminalId),+ ...(terminalId === DEFAULT_TERMINAL_ID ? [legacyHistoryPath(threadId)] : []),+ ]),+ ];++ const historyExists = (filePath: string) => {+ const name = path.basename(filePath);+ // An oversized old path can itself fail on access. Directory entries also+ // preserve migration of such histories on filesystems with a larger limit.+ return name.length <= MAX_HISTORY_FILENAME_BYTES+ ? fileSystem.exists(filePath)+ : fileSystem.readDirectory(logsDir).pipe(Effect.map((entries) => entries.includes(name)));+ };const readManagerState = SynchronizedRef.get(managerStateRef);@@ -2022,105 +2040,86 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(functerminalId: string,) {const nextPath = historyPath(threadId, terminalId);- if (- yield* fileSystem- .exists(nextPath)- .pipe(+ for (const sourcePath of historyPaths(threadId, terminalId)) {+ const migrating = sourcePath !== nextPath;+ const operation = migrating ? "migrate" : "read";+ if (+ !(yield* historyExists(sourcePath).pipe(Effect.mapError(- (cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),+ (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),),- )- ) {- const { history: raw, truncated } = yield* readHistoryTail(nextPath).pipe(+ ))+ )+ continue;+ const { history: raw, truncated } = yield* readHistoryTail(sourcePath).pipe(Effect.scoped,Effect.mapError(- (cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),+ (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),),);const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit);const capped = history.value();- if (truncated || capped !== raw) {- yield* fileSystem- .writeFileString(nextPath, capped)- .pipe(- Effect.mapError(- (cause) =>- new TerminalHistoryError({ operation: "truncate", threadId, terminalId, cause }),- ),- );- }- return history;- }-- if (terminalId !== DEFAULT_TERMINAL_ID || !hasLegacyHistoryPath(threadId)) {- return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);- }-- const legacyPath = legacyHistoryPath(threadId);- if (- !(yield* fileSystem- .exists(legacyPath)- .pipe(+ if (migrating || truncated || capped !== raw) {+ const write = migrating+ ? Effect.gen(function* () {+ const temporaryPath = yield* fileSystem.makeTempFileScoped({+ directory: logsDir,+ prefix: ".history-",+ });+ yield* fileSystem.writeFileString(temporaryPath, capped);+ yield* fileSystem.rename(temporaryPath, nextPath);+ }).pipe(Effect.scoped)+ : fileSystem.writeFileString(nextPath, capped);+ yield* write.pipe(Effect.mapError((cause) =>- new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),+ new TerminalHistoryError({+ operation: migrating ? "migrate" : "truncate",+ threadId,+ terminalId,+ cause,+ }),),- ))- ) {- return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);+ );+ }+ if (migrating) {+ yield* fileSystem.remove(sourcePath, { force: true }).pipe(+ Effect.catch((error) =>+ Effect.logWarning("failed to remove legacy terminal history", {+ threadId,+ terminalId,+ error,+ }),+ ),+ );+ }+ return history;}-- const { history: raw } = yield* readHistoryTail(legacyPath).pipe(- Effect.scoped,- Effect.mapError(- (cause) => new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),- ),- );- const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit);- const capped = history.value();- yield* fileSystem- .writeFileString(nextPath, capped)- .pipe(- Effect.mapError(- (cause) =>- new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),- ),- );- yield* fileSystem.remove(legacyPath, { force: true }).pipe(- Effect.catch((cleanupError) =>- Effect.logWarning("failed to remove legacy terminal history", {- threadId,- error: cleanupError,- }),- ),- );- return history;+ return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);});const deleteHistory = Effect.fn("terminal.deleteHistory")(function* (threadId: string,terminalId: string,) {- yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe(- Effect.catch((error) =>- Effect.logWarning("failed to delete terminal history", {- threadId,- terminalId,- error,- }),- ),- );- if (terminalId === DEFAULT_TERMINAL_ID && hasLegacyHistoryPath(threadId)) {- yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe(- Effect.catch((error) =>- Effect.logWarning("failed to delete terminal history", {- threadId,- terminalId,- error,- }),+ yield* Effect.forEach(+ historyPaths(threadId, terminalId),+ (filePath) =>+ Effect.gen(function* () {+ if (yield* historyExists(filePath)) {+ yield* fileSystem.remove(filePath, { force: true });+ }+ }).pipe(+ Effect.catch((error) =>+ Effect.logWarning("failed to delete terminal history", {+ threadId,+ terminalId,+ error,+ }),+ ),),- );- }+ { discard: true },+ );});const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* (