@devries-cameron20 / t3code Mirror · read-only / commits / a7d17cd2f5
Fork 0

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 21, 09:45 UTC

fix(server): session scan keeps recent Claude sessions in a large home (#37478)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

matthewcosier committed Nov 16, 2026 at 16:12 UTC a7d17cd2f5b76eb8132d320c0c1f1c357c15ec97
2 files changed +191 -20
apps/server/src/project/AgentSessionScanner.test.ts
+112
@@ -687,6 +687,118 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
687 }),
688 );
689
690 + it.effect("finds the newest Claude sessions in a large home beside empty ones", () =>
691 + Effect.gen(function* () {
692 + const path = yield* Path.Path;
693 + const claudeHomePath = yield* makeTempDir("t3code-claude-large-home-");
694 + const codexHomePath = yield* makeTempDir("t3code-codex-home-");
695 + const recentWorkspace = yield* makeTempDir("t3code-workspace-recent-");
696 + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
697 + // More project folders than the discovery budget reads, in an order unrelated to age.
698 + const folderCount = 12_000;
699 + const recentCount = 40;
700 + const newestMs = Date.parse("2026-03-01T00:00:00.000Z");
701 + yield* Effect.sync(() => {
702 + for (let index = 0; index < folderCount; index++) {
703 + const age = (index * 7_919) % folderCount;
704 + const directory = path.join(claudeHomePath, "projects", `-slug-${index}`);
705 + const filePath = path.join(directory, `session-${index}.jsonl`);
706 + const seconds = (newestMs - age * 60_000) / 1000;
707 + NodeFS.mkdirSync(directory, { recursive: true });
708 + NodeFS.writeFileSync(
709 + filePath,
710 + claudeSessionLine(age < recentCount ? recentWorkspace : olderWorkspace),
711 + );
712 + NodeFS.utimesSync(filePath, seconds, seconds);
713 + NodeFS.utimesSync(directory, seconds, seconds);
714 + }
715 + });
716 + const emptyHomes = [];
717 + for (let index = 0; index < 40; index++) {
718 + emptyHomes.push([
719 + ProviderInstanceId.make(`claude-empty-${index}`),
720 + {
721 + driver: ProviderDriverKind.make("claudeAgent"),
722 + config: { homePath: yield* makeTempDir(`t3code-claude-empty-${index}-`) },
723 + },
724 + ] as const);
725 + }
726 +
727 + const result = yield* runScan({
728 + claudeHomePath,
729 + codexHomePath,
730 + providerInstances: Object.fromEntries(emptyHomes),
731 + });
732 +
733 + expect(
734 + result.candidates.find((candidate) => candidate.path === recentWorkspace)?.threadCount,
735 + ).toBe(recentCount);
736 + }),
737 + );
738 +
739 + it.effect("passes budget a home frees while rescanning to the homes still short", () =>
740 + Effect.gen(function* () {
741 + const path = yield* Path.Path;
742 + const claudeHomePath = yield* makeTempDir("t3code-claude-empty-home-");
743 + const codexHomePath = yield* makeTempDir("t3code-codex-home-");
744 + const mediumHomePath = yield* makeTempDir("t3code-claude-medium-home-");
745 + const largeHomePath = yield* makeTempDir("t3code-claude-large-home-");
746 + const olderWorkspace = yield* makeTempDir("t3code-workspace-older-");
747 + const lastWorkspace = yield* makeTempDir("t3code-workspace-last-");
748 + const newestMs = Date.parse("2026-03-01T00:00:00.000Z");
749 + // Both homes outgrow their first share; together they fit the source's budget, but only
750 + // when what the medium home leaves over on its rescan reaches the large one, which is
751 + // listed first and so needs a second pass.
752 + yield* Effect.sync(() => {
753 + const writeSessions = (directory: string, count: number, cwd: string, ageMs: number) => {
754 + NodeFS.mkdirSync(directory, { recursive: true });
755 + const seconds = (newestMs - ageMs) / 1000;
756 + for (let index = 0; index < count; index++) {
757 + const filePath = path.join(directory, `session-${index}.jsonl`);
758 + NodeFS.writeFileSync(filePath, claudeSessionLine(cwd));
759 + NodeFS.utimesSync(filePath, seconds, seconds);
760 + }
761 + };
762 + writeSessions(
763 + path.join(mediumHomePath, "projects", "-medium"),
764 + 8_000,
765 + olderWorkspace,
766 + 60_000,
767 + );
768 + writeSessions(
769 + path.join(largeHomePath, "projects", "-bulk"),
770 + 11_000,
771 + olderWorkspace,
772 + 60_000,
773 + );
774 + // Read last because its folder is oldest, yet it holds the newest session.
775 + const lastDirectory = path.join(largeHomePath, "projects", "-last");
776 + writeSessions(lastDirectory, 1, lastWorkspace, 0);
777 + const oldSeconds = (newestMs - 3_600_000) / 1000;
778 + NodeFS.utimesSync(lastDirectory, oldSeconds, oldSeconds);
779 + });
780 +
781 + const result = yield* runScan({
782 + claudeHomePath,
783 + codexHomePath,
784 + providerInstances: {
785 + [ProviderInstanceId.make("claude-large")]: {
786 + driver: ProviderDriverKind.make("claudeAgent"),
787 + config: { homePath: largeHomePath },
788 + },
789 + [ProviderInstanceId.make("claude-medium")]: {
790 + driver: ProviderDriverKind.make("claudeAgent"),
791 + config: { homePath: mediumHomePath },
792 + },
793 + },
794 + });
795 +
796 + expect(
797 + result.candidates.find((candidate) => candidate.path === lastWorkspace)?.threadCount,
798 + ).toBe(1);
799 + }),
800 + );
801 +
802 it.effect("honors provider instance home directory environment variables", () =>
803 Effect.gen(function* () {
804 const path = yield* Path.Path;
apps/server/src/project/AgentSessionScanner.ts
+79 -20
@@ -273,6 +273,13 @@ interface MetadataReadBudget {
273 truncated: boolean;
274 }
275
276 +function splitOperationBudget(budget: number, count: number): Array<number> {
277 + return Array.from(
278 + { length: count },
279 + (_, index) => Math.floor(budget / count) + (index < budget % count ? 1 : 0),
280 + );
281 +}
282 +
283 function selectMetadataTranscripts(transcripts: ReadonlyArray<TranscriptCandidate>) {
284 const selected: Array<TranscriptCandidate> = [];
285 let pending = Array.from(
@@ -1395,7 +1402,35 @@ export const make = Effect.gen(function* () {
1402 operationsRemaining -= 1;
1403 return listDirectory(directory);
1404 };
1398 - const projectDirectories = yield* readDirectory(projectsDir);
1405 + // Folder names carry no date, so read the newest folders first: a budget that runs out
1406 + // then drops the oldest sessions. Dating has its own allowance, apart from the reads.
1407 + let datesRemaining = operationBudget;
1408 + const dated: Array<{ readonly name: string; readonly mtimeMs: number }> = [];
1409 + const undated: Array<string> = [];
1410 + for (const name of yield* readDirectory(projectsDir)) {
1411 + if (datesRemaining <= 0) {
1412 + undated.push(name);
1413 + continue;
1414 + }
1415 + datesRemaining -= 1;
1416 + const stats = yield* statOption(path.join(projectsDir, name));
1417 + if (Option.isNone(stats) || stats.value.type !== "Directory") continue;
1418 + dated.push({
1419 + name,
1420 + mtimeMs: Option.match(stats.value.mtime, {
1421 + onNone: () => 0,
1422 + onSome: (mtime) => mtime.getTime(),
1423 + }),
1424 + });
1425 + }
1426 + const projectDirectories = [
1427 + ...dated
1428 + .toSorted(
1429 + (left, right) => right.mtimeMs - left.mtimeMs || left.name.localeCompare(right.name),
1430 + )
1431 + .map((entry) => entry.name),
1432 + ...undated,
1433 + ];
1434 const transcripts: Array<TranscriptCandidate> = [];
1435
1436 for (const projectDirectory of projectDirectories) {
@@ -1431,7 +1466,7 @@ export const make = Effect.gen(function* () {
1466 });
1467 }
1468 }
1434 - return { transcripts, truncated };
1469 + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining };
1470 },
1471 );
1472
@@ -1550,6 +1585,7 @@ export const make = Effect.gen(function* () {
1585 return roots === undefined ? transcript : { ...transcript, projectRoots: roots };
1586 }),
1587 truncated,
1588 + operationsUsed: operationBudget - operationsRemaining,
1589 };
1590 },
1591 );
@@ -1605,7 +1641,7 @@ export const make = Effect.gen(function* () {
1641 }
1642 }
1643 }
1608 - return { transcripts, truncated };
1644 + return { transcripts, truncated, operationsUsed: operationBudget - operationsRemaining };
1645 });
1646
1647 const groupTranscriptsByCwd = Effect.fn("AgentSessionScanner.groupTranscriptsByCwd")(function* (
@@ -1773,25 +1809,48 @@ export const make = Effect.gen(function* () {
1809 }
1810
1811 const transcriptCandidates: Array<TranscriptCandidate> = [];
1776 - const baseOperationBudget = Math.floor(
1777 - MAX_DISCOVERY_OPERATIONS_PER_SOURCE / Math.max(1, homes.length),
1778 - );
1779 - const extraOperationBudgets = MAX_DISCOVERY_OPERATIONS_PER_SOURCE % Math.max(1, homes.length);
1812 + const discover =
1813 + source === "claudeAgent"
1814 + ? discoverClaudeTranscripts
1815 + : source === "codex"
1816 + ? discoverCodexTranscripts
1817 + : discoverPiTranscripts;
1818 + const shares = splitOperationBudget(MAX_DISCOVERY_OPERATIONS_PER_SOURCE, homes.length);
1819 + const discovered: Array<{
1820 + readonly transcripts: ReadonlyArray<TranscriptCandidate>;
1821 + readonly truncated: boolean;
1822 + readonly operationsUsed: number;
1823 + }> = [];
1824 for (const [index, home] of homes.entries()) {
1781 - const operationBudget = baseOperationBudget + (index < extraOperationBudgets ? 1 : 0);
1782 - if (operationBudget === 0) {
1783 - truncated = true;
1784 - continue;
1825 + const operationBudget = shares[index] ?? 0;
1826 + discovered.push(
1827 + operationBudget === 0
1828 + ? { transcripts: [], truncated: true, operationsUsed: 0 }
1829 + : yield* discover(home.homePath, home.providerInstanceId, operationBudget),
1830 + );
1831 + }
1832 + // Budget that small homes left unused goes to the homes that ran out, which rescan with it.
1833 + // Each takes an even split of what is still unused; a pass in which no home finishes spends
1834 + // it all, so every repeat has fewer starved homes.
1835 + let unused =
1836 + MAX_DISCOVERY_OPERATIONS_PER_SOURCE -
1837 + discovered.reduce((total, result) => total + result.operationsUsed, 0);
1838 + let starved = discovered.flatMap((result, index) => (result.truncated ? [index] : []));
1839 + while (unused > 0 && starved.length > 0) {
1840 + for (const [position, index] of starved.entries()) {
1841 + if (unused <= 0) break;
1842 + const home = homes[index]!;
1843 + const before = discovered[index]!.operationsUsed;
1844 + const extra = Math.ceil(unused / (starved.length - position));
1845 + const result = yield* discover(home.homePath, home.providerInstanceId, before + extra);
1846 + discovered[index] = result;
1847 + unused -= result.operationsUsed - before;
1848 }
1786 - const discover =
1787 - source === "claudeAgent"
1788 - ? discoverClaudeTranscripts
1789 - : source === "codex"
1790 - ? discoverCodexTranscripts
1791 - : discoverPiTranscripts;
1792 - const discovered = yield* discover(home.homePath, home.providerInstanceId, operationBudget);
1793 - truncated ||= discovered.truncated;
1794 - transcriptCandidates.push(...discovered.transcripts);
1849 + starved = starved.filter((index) => discovered[index]!.truncated);
1850 + }
1851 + for (const result of discovered) {
1852 + truncated ||= result.truncated;
1853 + transcriptCandidates.push(...result.transcripts);
1854 }
1855
1856 transcriptCandidates.sort(