Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions apps/server/src/assets/AssetAccess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { vi } from "vite-plus/test";

import * as AssetSigner from "./AssetSigner.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { sweepStalePendingAttachments } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
Expand Down Expand Up @@ -1276,6 +1277,33 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("keeps a draft's pending upload alive whenever a client asks for its URL", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
const now = 1_800_000_000_000;
const longAgo = DateTime.toDateUtc(DateTime.makeUnsafe(now - 60 * 24 * 60 * 60 * 1000));
const attachmentId = "pending-00000000-0000-4000-8000-000000000042-pdf";
const filePath = path.join(config.attachmentsDir, `${attachmentId}.pdf`);
const sidecarPath = `${filePath}.txt`;
for (const target of [filePath, sidecarPath]) {
yield* fileSystem.writeFileString(target, "draft");
yield* fileSystem.utimes(target, longAgo, longAgo);
}
yield* TestClock.setTime(now);

yield* issueAssetUrl({ resource: { _tag: "attachment", attachmentId } });

expect(
sweepStalePendingAttachments({ attachmentsDir: config.attachmentsDir, nowMs: now }),
).toEqual({ deleted: 0 });
expect(yield* fileSystem.exists(filePath)).toBe(true);
expect(yield* fileSystem.exists(sidecarPath)).toBe(true);
}).pipe(Effect.provide(layerTest)),
);

it.effect("serves document attachments inline when a viewer requests it", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
Expand Down
18 changes: 17 additions & 1 deletion apps/server/src/assets/AssetAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
import { isNetworkPath } from "@t3tools/shared/path";
import { MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH, toolOutputImages } from "@t3tools/shared/toolOutput";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Digest from "effect/crypto/Digest";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
Expand All @@ -50,7 +51,12 @@ import * as Stream from "effect/Stream";
import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
import * as AssetSigner from "./AssetSigner.ts";
import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
import {
parseAttachmentFileExtension,
parseThreadSegmentFromAttachmentId,
PENDING_ATTACHMENT_THREAD_SEGMENT,
resolveAttachmentPathById,
} from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
Expand Down Expand Up @@ -651,6 +657,16 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
resource: input.resource,
});
}
if (
parseThreadSegmentFromAttachmentId(input.resource.attachmentId) ===
PENDING_ATTACHMENT_THREAD_SEGMENT
) {
const touchedAt = DateTime.toDateUtc(yield* DateTime.now);
// Keeps the stale-upload sweep away from uploads an unsent draft still uses.
for (const target of [attachmentPath, `${attachmentPath}.txt`]) {
yield* fileSystem.utimes(target, touchedAt, touchedAt).pipe(Effect.ignore);
}
}
const extension = parseAttachmentFileExtension(input.resource.attachmentId);
const isGenericFile = extension !== null;
const videoMimeType = input.resource.mimeType?.split(";", 1)[0]?.trim() ?? "";
Expand Down
19 changes: 15 additions & 4 deletions apps/server/src/attachmentStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,22 +123,32 @@ describe("attachmentStore", () => {
}
});

it("removes expired pending and partial files without touching thread attachments", () => {
it("removes pending files untouched for 30 days and stale partials, keeping recent drafts", () => {
const attachmentsDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-sweep-"),
);
try {
const now = 1_800_000_000_000;
const oldTimeSeconds = (now - 2 * 24 * 60 * 60 * 1000) / 1000;
const daysAgoSeconds = (days: number) => (now - days * 24 * 60 * 60 * 1000) / 1000;
const uuid = "00000000-0000-4000-8000-000000000002";
const draftUuid = "00000000-0000-4000-8000-000000000003";
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.png`);
const pendingFilePath = NodePath.join(attachmentsDir, `pending-${uuid}-pdf.pdf`);
const sidecarPath = `${pendingFilePath}.txt`;
const threadPath = NodePath.join(attachmentsDir, `thread-1-${uuid}.png`);
const partialPath = NodePath.join(attachmentsDir, `${uuid}.part`);
for (const filePath of [pendingPath, pendingFilePath, sidecarPath, threadPath, partialPath]) {
// A draft's upload a few days old must survive; drafts live only on clients.
const draftPath = NodePath.join(attachmentsDir, `pending-${draftUuid}-pdf.pdf`);
for (const [filePath, days] of [
[pendingPath, 31],
[pendingFilePath, 31],
[sidecarPath, 31],
[threadPath, 31],
[partialPath, 2],
[draftPath, 2],
] as const) {
NodeFS.writeFileSync(filePath, Buffer.from("pixels"));
NodeFS.utimesSync(filePath, oldTimeSeconds, oldTimeSeconds);
NodeFS.utimesSync(filePath, daysAgoSeconds(days), daysAgoSeconds(days));
}

expect(sweepStalePendingAttachments({ attachmentsDir, nowMs: now })).toEqual({ deleted: 4 });
Expand All @@ -147,6 +157,7 @@ describe("attachmentStore", () => {
expect(NodeFS.existsSync(sidecarPath)).toBe(false);
expect(NodeFS.existsSync(partialPath)).toBe(false);
expect(NodeFS.existsSync(threadPath)).toBe(true);
expect(NodeFS.existsSync(draftPath)).toBe(true);
} finally {
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
}
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/attachmentStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ const ATTACHMENT_ID_PATTERN = new RegExp(
);

export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
// Unsent drafts live on clients, so the server cannot see which uploads they still reference.
// Clients ask for an upload's URL whenever a draft is opened, restored, or sent, which refreshes
// its timestamp; an upload untouched this long belongs to no draft anyone still opens.
const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;

export function toSafeThreadAttachmentSegment(threadId: string): string | null {
Expand Down
197 changes: 108 additions & 89 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15092,99 +15092,118 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);

it.effect("holds subagent frames that precede task_started and shows its result once", () =>
Effect.scoped(
Effect.gen(function* () {
const TASK_ID = "task-early-subagent";
const TOOL_USE_ID = "toolu-early-subagent";
const FINAL_REPORT = "Early auditor done.";
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-early-subagent"),
text: "Run an auditor.",
attachments: [],
}),
);
const frames = [
// Child frames can precede the task_started that registers their subagent.
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000321",
text: "Starting early.",
bashToolUseId: "toolu-early-bash",
}),
makeSubagentToolResultFrame({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000322",
toolUseId: "toolu-early-bash",
}),
makeSubagentTaskStartedFrame({
taskId: TASK_ID,
toolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000323",
}),
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000324",
text: "Still working.",
}),
claudeSdkFrame({
type: "system",
subtype: "task_progress",
task_id: TASK_ID,
description: "Checking the diffs",
uuid: "00000000-0000-4000-8000-000000000325",
session_id: WAKE_NATIVE_SESSION,
}),
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000326",
text: FINAL_REPORT,
}),
makeSubagentNotificationFrame({
taskId: TASK_ID,
toolUseId: TOOL_USE_ID,
summary: FINAL_REPORT,
uuid: "00000000-0000-4000-8000-000000000327",
}),
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000328",
result: "The auditor finished.",
}),
];
for (const frame of frames) {
yield* Queue.offer(harness.sdkMessages, frame);
}
yield* harness.awaitTerminal(1);
it.effect.each([
{ burst: "300 short messages", count: 300, size: 0, kept: 300 },
// The session buffers at most 64 MiB of early frames; the rest are dropped with a warning.
{ burst: "70 MiB of messages", count: 70, size: 1024 * 1024, kept: 63 },
])(
"holds subagent frames that precede task_started and shows its result once: $burst",
({ count, size, kept }) =>
Effect.scoped(
Effect.gen(function* () {
const TASK_ID = "task-early-subagent";
const TOOL_USE_ID = "toolu-early-subagent";
const FINAL_REPORT = "Early auditor done.";
const EARLY_BURST = Array.from(
{ length: count },
(_, index) => `Early ${index}.${"x".repeat(size)}`,
);
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-early-subagent"),
text: "Run an auditor.",
attachments: [],
}),
);
const frames = [
// Child frames can precede the task_started that registers their subagent.
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000321",
text: "Starting early.",
bashToolUseId: "toolu-early-bash",
}),
makeSubagentToolResultFrame({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000322",
toolUseId: "toolu-early-bash",
}),
// A long early burst still reaches the subagent once it registers.
...EARLY_BURST.flatMap((text, index) =>
makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: `00000000-0000-4000-8001-${String(index).padStart(12, "0")}`,
text,
}),
),
makeSubagentTaskStartedFrame({
taskId: TASK_ID,
toolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000323",
}),
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000324",
text: "Still working.",
}),
claudeSdkFrame({
type: "system",
subtype: "task_progress",
task_id: TASK_ID,
description: "Checking the diffs",
uuid: "00000000-0000-4000-8000-000000000325",
session_id: WAKE_NATIVE_SESSION,
}),
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000326",
text: FINAL_REPORT,
}),
makeSubagentNotificationFrame({
taskId: TASK_ID,
toolUseId: TOOL_USE_ID,
summary: FINAL_REPORT,
uuid: "00000000-0000-4000-8000-000000000327",
}),
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000328",
result: "The auditor finished.",
}),
];
for (const frame of frames) {
yield* Queue.offer(harness.sdkMessages, frame);
}
yield* harness.awaitTerminal(1);

const routing = subagentRouting(harness.events, ["toolu-early-bash"]);
assert.isDefined(routing.childThreadId);
assert.deepEqual(
[...(routing.toolThreadIds.get("toolu-early-bash") ?? [])],
[routing.childThreadId],
);
assert.deepEqual(routing.assistantTexts(routing.childThreadId), [
"Starting early.",
"Still working.",
FINAL_REPORT,
]);
assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
const routing = subagentRouting(harness.events, ["toolu-early-bash"]);
assert.isDefined(routing.childThreadId);
assert.deepEqual(
[...(routing.toolThreadIds.get("toolu-early-bash") ?? [])],
[routing.childThreadId],
);
assert.deepEqual(routing.assistantTexts(routing.childThreadId), [
"Starting early.",
...EARLY_BURST.slice(0, kept),
"Still working.",
FINAL_REPORT,
]);
assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]);
}).pipe(
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
),
),
);

it.effect.each([false, true])(
Expand Down
Loading
Loading