The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 12:00 UTC
fix(server): bound terminal history names for encrypted filesystems (#21654)
Co-authored-by: Le Jsessy <13083864+le-jsessy@user.noreply.gitee.com> Co-authored-by: maria-rcks <maria@kuuro.net>
JesstLe committed
Oct 31, 2026 at 04:28 UTC
32683c96f6911cb3219a14b31a19350dccff3075
2 files changed
+272
-99
apps/server/src/terminal/Manager.test.ts
+175
-1
@@ -1195,7 +1195,7 @@ it.layer(
1195
1196
it.effect("keeps reading and deleting history at an encoded path that already fit", () =>
1197
Effect.gen(function* () {
1198
- const threadId = "x".repeat(120);
1198
+ const threadId = "x".repeat(48);
1199
const { manager, logsDir } = yield* createManager();
1200
const fs = yield* FileSystem.FileSystem;
1201
const logPath = yield* historyLogPath(logsDir, threadId);
@@ -1213,6 +1213,180 @@ it.layer(
1213
}),
1214
);
1215
1216
+ it.effect.each([
1217
+ {
1218
+ label: "delegated setup",
1219
+ threadId:
1220
+ "thread:delegated-task:command%3Amcp%3A00000000-0000-4000-8000-000000000000%3Adelegate-task%3Aexample-r4-workspace-prepare-engine3",
1221
+ terminalId: "setup-setup-worktree-2",
1222
+ },
1223
+ { label: "long thread", threadId: "t".repeat(400), terminalId: DEFAULT_TERMINAL_ID },
1224
+ { label: "Unicode thread", threadId: "项目😀".repeat(60), terminalId: "setup" },
1225
+ { label: "long terminal", threadId: "short", terminalId: "t".repeat(128) },
1226
+ { label: "142-byte boundary", threadId: "t".repeat(48), terminalId: "s".repeat(48) },
1227
+ { label: "144-byte boundary", threadId: "t".repeat(49), terminalId: "s".repeat(48) },
1228
+ ])("persists $label history with a 143-byte filename limit", ({ threadId, terminalId }) =>
1229
+ Effect.gen(function* () {
1230
+ const fs = yield* FileSystem.FileSystem;
1231
+ const path = yield* Path.Path;
1232
+ const check = (filePath: string) =>
1233
+ Buffer.byteLength(path.basename(filePath)) <= 143
1234
+ ? Effect.void
1235
+ : Effect.fail(
1236
+ PlatformError.systemError({
1237
+ _tag: "Unknown",
1238
+ module: "FileSystem",
1239
+ method: "access",
1240
+ pathOrDescriptor: filePath,
1241
+ cause: { code: "ENAMETOOLONG" },
1242
+ }),
1243
+ );
1244
+ const limited = FileSystem.FileSystem.of({
1245
+ ...fs,
1246
+ exists: (filePath) => Effect.andThen(check(filePath), fs.exists(filePath)),
1247
+ open: (filePath, options) => Effect.andThen(check(filePath), fs.open(filePath, options)),
1248
+ writeFileString: (filePath, data, options) =>
1249
+ Effect.andThen(check(filePath), fs.writeFileString(filePath, data, options)),
1250
+ remove: (filePath, options) =>
1251
+ Effect.andThen(check(filePath), fs.remove(filePath, options)),
1252
+ });
1253
+ const { manager, ptyAdapter, logsDir } = yield* createManager().pipe(
1254
+ Effect.provideService(FileSystem.FileSystem, limited),
1255
+ );
1256
+ yield* manager.open(openInput({ threadId, terminalId }));
1257
+ ptyAdapter.processes[0]!.emitData("setup output\n");
1258
+ yield* manager.close({ threadId, terminalId });
1259
+ const names = yield* fs.readDirectory(logsDir);
1260
+ expect(names).toHaveLength(1);
1261
+ expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);
1262
+ expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(
1263
+ "setup output\n",
1264
+ );
1265
+ const otherThread = `${threadId}-other`;
1266
+ expect((yield* manager.open(openInput({ threadId: otherThread, terminalId }))).history).toBe(
1267
+ "",
1268
+ );
1269
+ ptyAdapter.processes[2]!.emitData("other output\n");
1270
+ yield* manager.close({ threadId: otherThread, terminalId });
1271
+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(2);
1272
+ yield* manager.close({ threadId, terminalId, deleteHistory: true });
1273
+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);
1274
+ yield* manager.close({ threadId: otherThread, deleteHistory: true });
1275
+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1276
+ }),
1277
+ );
1278
+
1279
+ it.effect.each([
1280
+ { source: "encoded", terminalId: DEFAULT_TERMINAL_ID },
1281
+ { source: "encoded", terminalId: "setup-setup-worktree-2" },
1282
+ { source: "sanitized", terminalId: DEFAULT_TERMINAL_ID },
1283
+ ])("migrates oversized $source history for $terminalId", ({ source, terminalId }) =>
1284
+ Effect.gen(function* () {
1285
+ const fs = yield* FileSystem.FileSystem;
1286
+ const path = yield* Path.Path;
1287
+ const { manager, logsDir } = yield* createManager();
1288
+ const threadId = "m".repeat(100);
1289
+ const oldPath =
1290
+ source === "encoded"
1291
+ ? path.join(
1292
+ logsDir,
1293
+ `terminal_${Base64Url.encode(threadId)}${terminalId === DEFAULT_TERMINAL_ID ? "" : `_${Base64Url.encode(terminalId)}`}.log`,
1294
+ )
1295
+ : path.join(logsDir, `${threadId}.log`);
1296
+ yield* fs.writeFileString(oldPath, "old output\n");
1297
+ expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(
1298
+ "old output\n",
1299
+ );
1300
+ const names = yield* fs.readDirectory(logsDir);
1301
+ expect(names).toHaveLength(1);
1302
+ expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);
1303
+ expect(yield* fs.exists(oldPath)).toBe(false);
1304
+ expect(yield* fs.readFileString(path.join(logsDir, names[0]!))).toBe("old output\n");
1305
+ yield* manager.close({ threadId, terminalId, deleteHistory: true });
1306
+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1307
+ }),
1308
+ );
1309
+
1310
+ it.effect.each(["terminal", "thread"] as const)(
1311
+ "deletes compact and older encoded history when closing a %s",
1312
+ (scope) =>
1313
+ Effect.gen(function* () {
1314
+ const fs = yield* FileSystem.FileSystem;
1315
+ const path = yield* Path.Path;
1316
+ const { manager, logsDir } = yield* createManager();
1317
+ const threadId = "d".repeat(100);
1318
+ const terminalId = "setup-setup-worktree-2";
1319
+ yield* manager.open(openInput({ threadId, terminalId }));
1320
+ yield* manager.close({ threadId, terminalId });
1321
+ const oldPath = path.join(
1322
+ logsDir,
1323
+ `terminal_${Base64Url.encode(threadId)}_${Base64Url.encode(terminalId)}.log`,
1324
+ );
1325
+ yield* fs.writeFileString(oldPath, "stale copy\n");
1326
+ yield* fs.writeFileString(path.join(logsDir, "unrelated.log"), "keep\n");
1327
+ if (scope === "terminal") {
1328
+ yield* manager.close({ threadId, terminalId, deleteHistory: true });
1329
+ } else {
1330
+ yield* manager.close({ threadId, deleteHistory: true });
1331
+ }
1332
+ expect(yield* fs.readDirectory(logsDir)).toEqual(["unrelated.log"]);
1333
+ }),
1334
+ );
1335
+
1336
+ it.effect("prefers bounded history over a stale encoded copy", () =>
1337
+ Effect.gen(function* () {
1338
+ const { manager, ptyAdapter, logsDir } = yield* createManager();
1339
+ const fs = yield* FileSystem.FileSystem;
1340
+ const threadId = "p".repeat(100);
1341
+ yield* manager.open(openInput({ threadId }));
1342
+ ptyAdapter.processes[0]!.emitData("current\n");
1343
+ yield* manager.close({ threadId });
1344
+ const oldPath = yield* historyLogPath(logsDir, threadId);
1345
+ yield* fs.writeFileString(oldPath, "stale\n");
1346
+
1347
+ expect((yield* manager.open(openInput({ threadId }))).history).toBe("current\n");
1348
+ yield* manager.close({ threadId, terminalId: DEFAULT_TERMINAL_ID, deleteHistory: true });
1349
+ expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1350
+ }),
1351
+ );
1352
+
1353
+ it.effect("retains encoded history if migration cannot write the bounded file", () =>
1354
+ Effect.gen(function* () {
1355
+ const fs = yield* FileSystem.FileSystem;
1356
+ let failNextWrite = true;
1357
+ const limited = FileSystem.FileSystem.of({
1358
+ ...fs,
1359
+ writeFileString: (filePath, data, options) => {
1360
+ if (!failNextWrite) return fs.writeFileString(filePath, data, options);
1361
+ failNextWrite = false;
1362
+ return fs.writeFileString(filePath, "partial").pipe(
1363
+ Effect.andThen(
1364
+ Effect.fail(
1365
+ PlatformError.systemError({
1366
+ _tag: "Unknown",
1367
+ module: "FileSystem",
1368
+ method: "writeFileString",
1369
+ cause: { code: "ENOSPC" },
1370
+ }),
1371
+ ),
1372
+ ),
1373
+ );
1374
+ },
1375
+ });
1376
+ const { manager, logsDir } = yield* createManager().pipe(
1377
+ Effect.provideService(FileSystem.FileSystem, limited),
1378
+ );
1379
+ const threadId = "f".repeat(100);
1380
+ const oldPath = yield* historyLogPath(logsDir, threadId);
1381
+ yield* fs.writeFileString(oldPath, "preserve me\n");
1382
+
1383
+ expect(Exit.isFailure(yield* Effect.exit(manager.open(openInput({ threadId }))))).toBe(true);
1384
+ expect(yield* fs.readFileString(oldPath)).toBe("preserve me\n");
1385
+ expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);
1386
+ expect((yield* manager.open(openInput({ threadId }))).history).toBe("preserve me\n");
1387
+ }),
1388
+ );
1389
+
1390
it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
1391
Effect.gen(function* () {
1392
const { manager, logsDir } = yield* createManager();
apps/server/src/terminal/Manager.ts
+97
-98
@@ -93,6 +93,8 @@ export {
93
94
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
95
const DEFAULT_HISTORY_BYTE_LIMIT = 8 * 1024 * 1024;
96
+// eCryptfs permits 143-byte names.
97
+const MAX_HISTORY_FILENAME_BYTES = 143;
98
const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
99
const DEFAULT_PERSIST_DEBOUNCE_MS = 250;
100
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
@@ -1304,8 +1306,6 @@ function legacySafeThreadId(threadId: string): string {
1306
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
1307
}
1308
1307
-const MAX_FILE_NAME_BYTES = 255;
1308
-
1309
function encodedHistoryThreadPart(threadId: string): string {
1310
return `terminal_${Base64Url.encode(threadId)}`;
1311
}
@@ -1672,28 +1672,46 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1672
}
1673
});
1674
1675
- // Nested subagent thread ids can encode past the filename limit. Only names that would not fit
1676
- // switch to hashed ids, so every history file that already exists keeps its path.
1677
- const historyPath = (threadId: string, terminalId: string) => {
1678
- const isDefault = terminalId === DEFAULT_TERMINAL_ID;
1679
- const encodedName = joinHistoryFileName(
1680
- encodedHistoryThreadPart(threadId),
1681
- isDefault ? null : Base64Url.encode(terminalId),
1675
+ const encodedHistoryPath = (threadId: string, terminalId: string) =>
1676
+ path.join(
1677
+ logsDir,
1678
+ joinHistoryFileName(
1679
+ encodedHistoryThreadPart(threadId),
1680
+ terminalId === DEFAULT_TERMINAL_ID ? null : Base64Url.encode(terminalId),
1681
+ ),
1682
);
1683
- if (encodedName.length <= MAX_FILE_NAME_BYTES) {
1684
- return path.join(logsDir, encodedName);
1685
- }
1683
+
1684
+ const historyPath = (threadId: string, terminalId: string) => {
1685
+ const encoded = encodedHistoryPath(threadId, terminalId);
1686
+ if (path.basename(encoded).length <= MAX_HISTORY_FILENAME_BYTES) return encoded;
1687
return path.join(
1688
logsDir,
1688
- joinHistoryFileName(hashedHistoryThreadPart(threadId), isDefault ? null : hashId(terminalId)),
1689
+ joinHistoryFileName(
1690
+ hashedHistoryThreadPart(threadId),
1691
+ terminalId === DEFAULT_TERMINAL_ID ? null : hashId(terminalId),
1692
+ ),
1693
);
1694
};
1695
1692
- const legacyHistoryName = (threadId: string) => `${legacySafeThreadId(threadId)}.log`;
1693
- const legacyHistoryPath = (threadId: string) => path.join(logsDir, legacyHistoryName(threadId));
1694
- // Ids this long could never have been written under the legacy name.
1695
- const hasLegacyHistoryPath = (threadId: string) =>
1696
- Buffer.byteLength(legacyHistoryName(threadId)) <= MAX_FILE_NAME_BYTES;
1696
+ const legacyHistoryPath = (threadId: string) =>
1697
+ path.join(logsDir, `${legacySafeThreadId(threadId)}.log`);
1698
+
1699
+ const historyPaths = (threadId: string, terminalId: string) => [
1700
+ ...new Set([
1701
+ historyPath(threadId, terminalId),
1702
+ encodedHistoryPath(threadId, terminalId),
1703
+ ...(terminalId === DEFAULT_TERMINAL_ID ? [legacyHistoryPath(threadId)] : []),
1704
+ ]),
1705
+ ];
1706
+
1707
+ const historyExists = (filePath: string) => {
1708
+ const name = path.basename(filePath);
1709
+ // An oversized old path can itself fail on access. Directory entries also
1710
+ // preserve migration of such histories on filesystems with a larger limit.
1711
+ return name.length <= MAX_HISTORY_FILENAME_BYTES
1712
+ ? fileSystem.exists(filePath)
1713
+ : fileSystem.readDirectory(logsDir).pipe(Effect.map((entries) => entries.includes(name)));
1714
+ };
1715
1716
const readManagerState = SynchronizedRef.get(managerStateRef);
1717
@@ -2022,105 +2040,86 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2040
terminalId: string,
2041
) {
2042
const nextPath = historyPath(threadId, terminalId);
2025
- if (
2026
- yield* fileSystem
2027
- .exists(nextPath)
2028
- .pipe(
2043
+ for (const sourcePath of historyPaths(threadId, terminalId)) {
2044
+ const migrating = sourcePath !== nextPath;
2045
+ const operation = migrating ? "migrate" : "read";
2046
+ if (
2047
+ !(yield* historyExists(sourcePath).pipe(
2048
Effect.mapError(
2030
- (cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),
2049
+ (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),
2050
),
2032
- )
2033
- ) {
2034
- const { history: raw, truncated } = yield* readHistoryTail(nextPath).pipe(
2051
+ ))
2052
+ )
2053
+ continue;
2054
+ const { history: raw, truncated } = yield* readHistoryTail(sourcePath).pipe(
2055
Effect.scoped,
2056
Effect.mapError(
2037
- (cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),
2057
+ (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),
2058
),
2059
);
2060
const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit);
2061
const capped = history.value();
2042
- if (truncated || capped !== raw) {
2043
- yield* fileSystem
2044
- .writeFileString(nextPath, capped)
2045
- .pipe(
2046
- Effect.mapError(
2047
- (cause) =>
2048
- new TerminalHistoryError({ operation: "truncate", threadId, terminalId, cause }),
2049
- ),
2050
- );
2051
- }
2052
- return history;
2053
- }
2054
-
2055
- if (terminalId !== DEFAULT_TERMINAL_ID || !hasLegacyHistoryPath(threadId)) {
2056
- return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);
2057
- }
2058
-
2059
- const legacyPath = legacyHistoryPath(threadId);
2060
- if (
2061
- !(yield* fileSystem
2062
- .exists(legacyPath)
2063
- .pipe(
2062
+ if (migrating || truncated || capped !== raw) {
2063
+ const write = migrating
2064
+ ? Effect.gen(function* () {
2065
+ const temporaryPath = yield* fileSystem.makeTempFileScoped({
2066
+ directory: logsDir,
2067
+ prefix: ".history-",
2068
+ });
2069
+ yield* fileSystem.writeFileString(temporaryPath, capped);
2070
+ yield* fileSystem.rename(temporaryPath, nextPath);
2071
+ }).pipe(Effect.scoped)
2072
+ : fileSystem.writeFileString(nextPath, capped);
2073
+ yield* write.pipe(
2074
Effect.mapError(
2075
(cause) =>
2066
- new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
2076
+ new TerminalHistoryError({
2077
+ operation: migrating ? "migrate" : "truncate",
2078
+ threadId,
2079
+ terminalId,
2080
+ cause,
2081
+ }),
2082
),
2068
- ))
2069
- ) {
2070
- return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);
2083
+ );
2084
+ }
2085
+ if (migrating) {
2086
+ yield* fileSystem.remove(sourcePath, { force: true }).pipe(
2087
+ Effect.catch((error) =>
2088
+ Effect.logWarning("failed to remove legacy terminal history", {
2089
+ threadId,
2090
+ terminalId,
2091
+ error,
2092
+ }),
2093
+ ),
2094
+ );
2095
+ }
2096
+ return history;
2097
}
2072
-
2073
- const { history: raw } = yield* readHistoryTail(legacyPath).pipe(
2074
- Effect.scoped,
2075
- Effect.mapError(
2076
- (cause) => new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
2077
- ),
2078
- );
2079
- const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit);
2080
- const capped = history.value();
2081
- yield* fileSystem
2082
- .writeFileString(nextPath, capped)
2083
- .pipe(
2084
- Effect.mapError(
2085
- (cause) =>
2086
- new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
2087
- ),
2088
- );
2089
- yield* fileSystem.remove(legacyPath, { force: true }).pipe(
2090
- Effect.catch((cleanupError) =>
2091
- Effect.logWarning("failed to remove legacy terminal history", {
2092
- threadId,
2093
- error: cleanupError,
2094
- }),
2095
- ),
2096
- );
2097
- return history;
2098
+ return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);
2099
});
2100
2101
const deleteHistory = Effect.fn("terminal.deleteHistory")(function* (
2102
threadId: string,
2103
terminalId: string,
2104
) {
2104
- yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe(
2105
- Effect.catch((error) =>
2106
- Effect.logWarning("failed to delete terminal history", {
2107
- threadId,
2108
- terminalId,
2109
- error,
2110
- }),
2111
- ),
2112
- );
2113
- if (terminalId === DEFAULT_TERMINAL_ID && hasLegacyHistoryPath(threadId)) {
2114
- yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe(
2115
- Effect.catch((error) =>
2116
- Effect.logWarning("failed to delete terminal history", {
2117
- threadId,
2118
- terminalId,
2119
- error,
2120
- }),
2105
+ yield* Effect.forEach(
2106
+ historyPaths(threadId, terminalId),
2107
+ (filePath) =>
2108
+ Effect.gen(function* () {
2109
+ if (yield* historyExists(filePath)) {
2110
+ yield* fileSystem.remove(filePath, { force: true });
2111
+ }
2112
+ }).pipe(
2113
+ Effect.catch((error) =>
2114
+ Effect.logWarning("failed to delete terminal history", {
2115
+ threadId,
2116
+ terminalId,
2117
+ error,
2118
+ }),
2119
+ ),
2120
),
2122
- );
2123
- }
2121
+ { discard: true },
2122
+ );
2123
});
2124
2125
const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* (