Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36f6d76bd5 | ||
|
|
03196ef7ad | ||
|
|
f695b6f5bf |
No files matched your search
@@ -95,12 +95,15 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
|
||||
const handleNativePaste = useNativePaste((uris) => {
|
||||
void (async () => {
|
||||
try {
|
||||
const images = await convertPastedImagesToAttachments({
|
||||
const pasted = await convertPastedImagesToAttachments({
|
||||
uris,
|
||||
existingCount: attachments.length,
|
||||
});
|
||||
if (images.length > 0) {
|
||||
setAttachments((current) => [...current, ...images]);
|
||||
if (pasted.images.length > 0) {
|
||||
setAttachments((current) => [...current, ...pasted.images]);
|
||||
}
|
||||
if (pasted.error) {
|
||||
setPendingConnectionError(pasted.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[review comment] error converting pasted images", error);
|
||||
|
||||
@@ -54,7 +54,10 @@ import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
setPendingConnectionError,
|
||||
useRemoteConnectionStatus,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
@@ -607,17 +610,23 @@ export function NewTaskDraftScreen(props: {
|
||||
if (result.images.length > 0) {
|
||||
flow.appendAttachments(result.images);
|
||||
}
|
||||
if (result.error) {
|
||||
setPendingConnectionError(result.error);
|
||||
}
|
||||
}
|
||||
|
||||
const handleNativePasteImages = useCallback(
|
||||
async (uris: ReadonlyArray<string>) => {
|
||||
try {
|
||||
const images = await convertPastedImagesToAttachments({
|
||||
const pasted = await convertPastedImagesToAttachments({
|
||||
uris,
|
||||
existingCount: flow.attachments.length,
|
||||
});
|
||||
if (images.length > 0) {
|
||||
flow.appendAttachments(images);
|
||||
if (pasted.images.length > 0) {
|
||||
flow.appendAttachments(pasted.images);
|
||||
}
|
||||
if (pasted.error) {
|
||||
setPendingConnectionError(pasted.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[native paste] error converting images", error);
|
||||
|
||||
@@ -14,7 +14,10 @@ import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import {
|
||||
droppedAttachmentsWarning,
|
||||
type DraftComposerImageAttachment,
|
||||
} from "../../lib/composerImages";
|
||||
import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
|
||||
import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
|
||||
import { randomHex } from "../../lib/uuid";
|
||||
@@ -84,7 +87,11 @@ export function useCreateProjectThread() {
|
||||
);
|
||||
return AsyncResult.failure(result.cause);
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
// Legacy drafts can still carry data-url images. `thread.turn.start` now
|
||||
// only accepts uploaded attachment ids, which mobile cannot mint yet, so
|
||||
// those images are dropped and the user is told rather than left to
|
||||
// assume they were sent. Null clears the banner when there are none.
|
||||
setPendingConnectionError(droppedAttachmentsWarning(input.initialAttachments.length));
|
||||
|
||||
return mapAtomCommandResult(result, () =>
|
||||
scopeThreadRef(input.project.environmentId, threadId),
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
|
||||
|
||||
const files = new Map<string, { base64: string; deleted: boolean }>();
|
||||
|
||||
@@ -38,33 +37,22 @@ vi.mock("./uuid", () => ({
|
||||
|
||||
import {
|
||||
convertPastedImagesToAttachments,
|
||||
droppedAttachmentsWarning,
|
||||
isOwnedPastedImageUri,
|
||||
toUploadChatImageAttachments,
|
||||
} from "./composerImages";
|
||||
|
||||
describe("toUploadChatImageAttachments", () => {
|
||||
it("strips client draft id and previewUri for the startTurn wire shape", () => {
|
||||
expect(
|
||||
toUploadChatImageAttachments([
|
||||
{
|
||||
id: "client-draft-id",
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
previewUri: "file:///tmp/preview.png",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
type: "image",
|
||||
name: "pasted-image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 12,
|
||||
dataUrl: "data:image/png;base64,AA==",
|
||||
},
|
||||
]);
|
||||
describe("droppedAttachmentsWarning", () => {
|
||||
it("stays quiet when a message carries no legacy images", () => {
|
||||
expect(droppedAttachmentsWarning(0)).toBeNull();
|
||||
});
|
||||
|
||||
it("names how many legacy images were left behind", () => {
|
||||
expect(droppedAttachmentsWarning(1)).toBe(
|
||||
"1 image was not sent. Image attach needs an app update.",
|
||||
);
|
||||
expect(droppedAttachmentsWarning(3)).toBe(
|
||||
"3 images were not sent. Image attach needs an app update.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -83,42 +71,24 @@ describe("native pasted image cleanup", () => {
|
||||
expect(isOwnedPastedImageUri("https://example.com/t3-composer-paste/id.png")).toBe(false);
|
||||
});
|
||||
|
||||
it("converts owned files to data-backed previews and deletes the source", async () => {
|
||||
const uri =
|
||||
// Image attach is off until mobile implements upload-on-attach, so pasted
|
||||
// images produce no attachment. Temp-file cleanup must still happen.
|
||||
it("attaches nothing and deletes owned temp files, leaving user files alone", async () => {
|
||||
const owned =
|
||||
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
|
||||
files.set(uri, { base64: "aGVsbG8=", deleted: false });
|
||||
const userOwned = "file:///private/var/mobile/photos/library.png";
|
||||
files.set(owned, { base64: "aGVsbG8=", deleted: false });
|
||||
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
|
||||
|
||||
const attachments = await convertPastedImagesToAttachments({
|
||||
uris: [uri],
|
||||
const pasted = await convertPastedImagesToAttachments({
|
||||
uris: [owned, userOwned],
|
||||
existingCount: 0,
|
||||
});
|
||||
|
||||
expect(attachments).toEqual([
|
||||
expect.objectContaining({
|
||||
dataUrl: "data:image/png;base64,aGVsbG8=",
|
||||
previewUri: "data:image/png;base64,aGVsbG8=",
|
||||
}),
|
||||
]);
|
||||
expect(files.get(uri)?.deleted).toBe(true);
|
||||
});
|
||||
|
||||
it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
|
||||
const rejected =
|
||||
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
|
||||
const overflow =
|
||||
"file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
|
||||
const userOwned = "file:///private/var/mobile/photos/library.png";
|
||||
files.set(rejected, { base64: "", deleted: false });
|
||||
files.set(overflow, { base64: "aGVsbG8=", deleted: false });
|
||||
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
|
||||
|
||||
await convertPastedImagesToAttachments({
|
||||
uris: [rejected, overflow, userOwned],
|
||||
existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
|
||||
});
|
||||
|
||||
expect(files.get(rejected)?.deleted).toBe(true);
|
||||
expect(files.get(overflow)?.deleted).toBe(true);
|
||||
expect(pasted.images).toEqual([]);
|
||||
// The drop is surfaced to callers, not just logged.
|
||||
expect(pasted.error).toContain("app update");
|
||||
expect(files.get(owned)?.deleted).toBe(true);
|
||||
expect(files.get(userOwned)?.deleted).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,29 +1,46 @@
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type UploadChatImageAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import { estimateBase64ByteSize } from "./base64";
|
||||
import { uuidv4 } from "./uuid";
|
||||
|
||||
export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
|
||||
/**
|
||||
* Local-only draft shape. It used to extend the contracts upload type, but
|
||||
* `thread.turn.start` now carries id references to already-uploaded blobs, so
|
||||
* `dataUrl` never reaches the wire and lives purely in mobile draft storage.
|
||||
*/
|
||||
export interface DraftComposerImageAttachment {
|
||||
readonly id: string;
|
||||
readonly previewUri: string;
|
||||
readonly type: "image";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly dataUrl: string;
|
||||
}
|
||||
|
||||
/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
|
||||
export function toUploadChatImageAttachments(
|
||||
attachments: ReadonlyArray<DraftComposerImageAttachment>,
|
||||
): ReadonlyArray<UploadChatImageAttachment> {
|
||||
return attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
dataUrl: attachment.dataUrl,
|
||||
}));
|
||||
export const IMAGE_ATTACH_UNAVAILABLE_MESSAGE = "Image attach needs an app update.";
|
||||
|
||||
/**
|
||||
* Copy for legacy draft/outbox images that predate the contract change and so
|
||||
* cannot be sent. Returns null when there is nothing to warn about.
|
||||
*/
|
||||
export function droppedAttachmentsWarning(count: number): string | null {
|
||||
if (count <= 0) {
|
||||
return null;
|
||||
}
|
||||
const subject = count === 1 ? "1 image was" : `${count} images were`;
|
||||
return `${subject} not sent. ${IMAGE_ATTACH_UNAVAILABLE_MESSAGE}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile has no upload-on-attach implementation yet (web shipped first), and
|
||||
* the old data-url path is gone from the contract. Capture stays disabled
|
||||
* until the mobile port lands; flip this back on with that change.
|
||||
*/
|
||||
const IMAGE_ATTACH_ENABLED: boolean = false;
|
||||
|
||||
const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
|
||||
|
||||
async function loadImagePicker() {
|
||||
@@ -46,6 +63,10 @@ export async function pickComposerImages(input: { readonly existingCount: number
|
||||
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly error: string | null;
|
||||
}> {
|
||||
if (!IMAGE_ATTACH_ENABLED) {
|
||||
return { images: [], error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
|
||||
}
|
||||
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
@@ -137,7 +158,7 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
|
||||
if (await clipboard.hasImageAsync()) {
|
||||
if ((await clipboard.hasImageAsync()) && IMAGE_ATTACH_ENABLED) {
|
||||
if (remainingSlots <= 0) {
|
||||
return {
|
||||
images: [],
|
||||
@@ -181,14 +202,26 @@ export async function pasteComposerClipboard(input: { readonly existingCount: nu
|
||||
};
|
||||
}
|
||||
|
||||
// Reached with attach disabled even when the clipboard holds an image:
|
||||
// mixed copy payloads (common on iOS) must still paste their text, with
|
||||
// the image drop surfaced rather than silently swallowed.
|
||||
if (await clipboard.hasStringAsync()) {
|
||||
const text = await clipboard.getStringAsync();
|
||||
const droppedImage = !IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync());
|
||||
return {
|
||||
images: [],
|
||||
text: text.length > 0 ? text : null,
|
||||
error: text.length > 0 ? null : "Clipboard is empty.",
|
||||
error: droppedImage
|
||||
? IMAGE_ATTACH_UNAVAILABLE_MESSAGE
|
||||
: text.length > 0
|
||||
? null
|
||||
: "Clipboard is empty.",
|
||||
};
|
||||
}
|
||||
if (!IMAGE_ATTACH_ENABLED && (await clipboard.hasImageAsync())) {
|
||||
// Image-only clipboard while attach is disabled.
|
||||
return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };
|
||||
}
|
||||
|
||||
return {
|
||||
images: [],
|
||||
@@ -234,9 +267,19 @@ export function isOwnedPastedImageUri(uri: string): boolean {
|
||||
export async function convertPastedImagesToAttachments(input: {
|
||||
readonly uris: ReadonlyArray<string>;
|
||||
readonly existingCount: number;
|
||||
}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
|
||||
}): Promise<{
|
||||
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
/** Set when pasted images were dropped; callers surface it like a pick error. */
|
||||
readonly error: string | null;
|
||||
}> {
|
||||
const { File } = await import("expo-file-system");
|
||||
const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
|
||||
// Zero slots while attach is disabled: the loop below still runs so owned
|
||||
// temporary paste files are deleted, but nothing is decoded or attached.
|
||||
const remainingSlots = IMAGE_ATTACH_ENABLED
|
||||
? PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount
|
||||
: 0;
|
||||
const error =
|
||||
!IMAGE_ATTACH_ENABLED && input.uris.length > 0 ? IMAGE_ATTACH_UNAVAILABLE_MESSAGE : null;
|
||||
const results: DraftComposerImageAttachment[] = [];
|
||||
|
||||
for (const [index, uri] of input.uris.entries()) {
|
||||
@@ -277,5 +320,5 @@ export async function convertPastedImagesToAttachments(input: {
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
return { images: results, error };
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
|
||||
import type { DraftComposerImageAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
@@ -28,6 +28,11 @@ export interface ProjectThreadStartTurnSpec {
|
||||
readonly messageId: string;
|
||||
readonly createdAt: string;
|
||||
readonly text: string;
|
||||
/**
|
||||
* Legacy data-url drafts only. `thread.turn.start` now takes id references
|
||||
* to uploaded blobs, which mobile cannot mint yet, so these are dropped
|
||||
* rather than sent. Callers surface `droppedAttachmentsWarning` to the user.
|
||||
*/
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
@@ -55,7 +60,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
role: "user" as const,
|
||||
text: spec.text,
|
||||
attachments: toUploadChatImageAttachments(spec.attachments),
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: spec.modelSelection,
|
||||
titleSeed: title,
|
||||
|
||||
@@ -238,12 +238,15 @@ export function useThreadComposerState() {
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
try {
|
||||
const images = await convertPastedImagesToAttachments({
|
||||
const pasted = await convertPastedImagesToAttachments({
|
||||
uris,
|
||||
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
|
||||
});
|
||||
if (images.length > 0) {
|
||||
appendComposerDraftAttachments(threadKey, images);
|
||||
if (pasted.images.length > 0) {
|
||||
appendComposerDraftAttachments(threadKey, pasted.images);
|
||||
}
|
||||
if (pasted.error) {
|
||||
setPendingConnectionError(pasted.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[native paste] error converting images", {
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
|
||||
import { toUploadChatImageAttachments } from "../lib/composerImages";
|
||||
import { droppedAttachmentsWarning } from "../lib/composerImages";
|
||||
import { randomHex } from "../lib/uuid";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useProjects, useThreadShells } from "./entities";
|
||||
@@ -44,7 +44,10 @@ import {
|
||||
useThreadOutboxMessages,
|
||||
useThreadOutboxShellStatuses,
|
||||
} from "./use-thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
|
||||
import {
|
||||
setPendingConnectionError,
|
||||
useRemoteConnectionStatus,
|
||||
} from "./use-remote-environment-registry";
|
||||
|
||||
export const dispatchingQueuedMessageIdAtom = Atom.make<MessageId | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -149,6 +152,14 @@ export function useThreadOutboxDrain(): void {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Messages queued before the attachment contract change can still hold
|
||||
// data-url images. They are never put on the wire, so tell the user the
|
||||
// text went without them instead of dropping them silently.
|
||||
const droppedWarning = droppedAttachmentsWarning(queuedMessage.attachments.length);
|
||||
if (droppedWarning !== null) {
|
||||
setPendingConnectionError(droppedWarning);
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
@@ -226,7 +237,7 @@ export function useThreadOutboxDrain(): void {
|
||||
messageId: queuedMessage.messageId,
|
||||
role: "user",
|
||||
text: queuedMessage.text,
|
||||
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { parseThreadSegmentFromAttachmentId } from "../attachmentStore.ts";
|
||||
import {
|
||||
deletePendingAttachment,
|
||||
issueAttachmentUploadUrl,
|
||||
storeAttachmentUpload,
|
||||
validateAttachmentUploadToken,
|
||||
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
|
||||
} from "./AttachmentUpload.ts";
|
||||
|
||||
const testLayer = ServerSecretStore.layer.pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const uploadInput = {
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 6,
|
||||
} as const;
|
||||
|
||||
describe("AttachmentUpload", () => {
|
||||
it.effect("mints a pending id and a token that validates round-trip", () =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
expect(parseThreadSegmentFromAttachmentId(issued.attachmentId)).toBe("pending");
|
||||
expect(issued.relativeUrl.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`)).toBe(true);
|
||||
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
expect(claims).toMatchObject({
|
||||
kind: "attachment-upload",
|
||||
attachmentId: issued.attachmentId,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 6,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects a tampered token", () =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const [payload, signature] = token.split(".");
|
||||
const tampered = `${payload}x.${signature}`;
|
||||
expect(yield* validateAttachmentUploadToken(tampered)).toBeNull();
|
||||
expect(yield* validateAttachmentUploadToken("garbage")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("stores matching bytes and rejects a size mismatch", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const issued = yield* issueAttachmentUploadUrl(uploadInput);
|
||||
const token = issued.relativeUrl.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
if (!claims) throw new Error("expected valid claims");
|
||||
|
||||
const short = yield* storeAttachmentUpload(claims, new Uint8Array([1, 2, 3]));
|
||||
expect(short).toMatchObject({ ok: false, status: 400 });
|
||||
|
||||
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(6));
|
||||
expect(stored).toEqual({ ok: true });
|
||||
const finalPath = NodePath.join(config.attachmentsDir, `${issued.attachmentId}.png`);
|
||||
expect(NodeFS.existsSync(finalPath)).toBe(true);
|
||||
// No .part residue after a successful store (suffix is per-request).
|
||||
const partResidue = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
|
||||
entry.endsWith(".part"),
|
||||
);
|
||||
expect(partResidue).toEqual([]);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("deletes pending uploads idempotently but never thread-scoped files", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
|
||||
const uuid = "00000000-0000-4000-8000-0000000000dd";
|
||||
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${uuid}.png`);
|
||||
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
|
||||
|
||||
yield* deletePendingAttachment(`pending-${uuid}`);
|
||||
expect(NodeFS.existsSync(pendingPath)).toBe(false);
|
||||
// Second delete is a no-op, not an error.
|
||||
yield* deletePendingAttachment(`pending-${uuid}`);
|
||||
|
||||
const scopedUuid = "00000000-0000-4000-8000-0000000000ee";
|
||||
const scopedPath = NodePath.join(config.attachmentsDir, `thread-1-${scopedUuid}.png`);
|
||||
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
|
||||
// A delete aimed at a claimed attachment must not remove it.
|
||||
yield* deletePendingAttachment(`pending-${scopedUuid}`);
|
||||
yield* deletePendingAttachment(`thread-1-${scopedUuid}`);
|
||||
expect(NodeFS.existsSync(scopedPath)).toBe(true);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import {
|
||||
ATTACHMENT_UPLOAD_URL_TTL_MS,
|
||||
type AttachmentCreateUploadUrlInput,
|
||||
AttachmentUploadSigningKeyError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
createPendingAttachmentId,
|
||||
findAttachmentPathByUuid,
|
||||
parseAttachmentIdFromRelativePath,
|
||||
parseAttachmentUuid,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
PENDING_ATTACHMENT_THREAD_SEGMENT,
|
||||
} from "../attachmentStore.ts";
|
||||
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../auth/utils.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { inferImageExtension } from "../imageMime.ts";
|
||||
|
||||
export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
|
||||
|
||||
// Shares the asset-access secret: upload and asset claims are distinguished
|
||||
// by their schema `kind`, so a token minted for one can never validate as
|
||||
// the other, and one key covers both signing uses.
|
||||
const SIGNING_SECRET_NAME = "asset-access-signing-key";
|
||||
|
||||
const UploadClaimsSchema = Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("attachment-upload"),
|
||||
attachmentId: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
/** Exact byte count the client committed to at mint time. */
|
||||
sizeBytes: Schema.Number,
|
||||
expiresAt: Schema.Number,
|
||||
});
|
||||
export type AttachmentUploadClaims = typeof UploadClaimsSchema.Type;
|
||||
|
||||
const UploadClaimsJson = Schema.fromJsonString(UploadClaimsSchema);
|
||||
const decodeUploadClaimsOption = Schema.decodeUnknownOption(UploadClaimsJson);
|
||||
const encodeUploadClaims = Schema.encodeSync(UploadClaimsJson);
|
||||
|
||||
// Plain function (not Effect) so the base64/JSON failure modes stay a simple
|
||||
// null, mirroring AssetAccess.decodeClaims.
|
||||
function decodeUploadClaims(encodedPayload: string): AttachmentUploadClaims | null {
|
||||
try {
|
||||
return Option.getOrNull(decodeUploadClaimsOption(base64UrlDecodeUtf8(encodedPayload)));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const loadSigningSecret = Effect.gen(function* () {
|
||||
const secretStore = yield* ServerSecretStore.ServerSecretStore;
|
||||
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
});
|
||||
|
||||
/**
|
||||
* Mints the `pending-<uuid>` id and a signed, expiring upload URL for it.
|
||||
* Called over the authenticated ws; the returned URL itself carries
|
||||
* authorization (mirroring signed asset GET URLs), which is what lets the
|
||||
* browser POST bytes to any environment without extra credential plumbing.
|
||||
*/
|
||||
export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
|
||||
input: AttachmentCreateUploadUrlInput,
|
||||
) {
|
||||
const secret = yield* loadSigningSecret.pipe(
|
||||
Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
|
||||
);
|
||||
const attachmentId = createPendingAttachmentId();
|
||||
const expiresAt = (yield* Clock.currentTimeMillis) + ATTACHMENT_UPLOAD_URL_TTL_MS;
|
||||
const encodedPayload = base64UrlEncode(
|
||||
encodeUploadClaims({
|
||||
version: 1,
|
||||
kind: "attachment-upload",
|
||||
attachmentId,
|
||||
mimeType: input.mimeType.toLowerCase(),
|
||||
sizeBytes: input.sizeBytes,
|
||||
expiresAt,
|
||||
}),
|
||||
);
|
||||
const token = `${encodedPayload}.${signPayload(encodedPayload, secret)}`;
|
||||
return {
|
||||
attachmentId,
|
||||
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${token}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
|
||||
/** Verifies signature and expiry; null means "treat as not found". */
|
||||
export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validateToken")(function* (
|
||||
token: string,
|
||||
) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) return null;
|
||||
|
||||
const secret = yield* loadSigningSecret.pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to load the attachment upload signing key.", { cause }),
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
if (!secret) return null;
|
||||
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) return null;
|
||||
|
||||
const claims = decodeUploadClaims(encodedPayload);
|
||||
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
|
||||
return claims;
|
||||
});
|
||||
|
||||
export type StoreUploadResult =
|
||||
| { readonly ok: true }
|
||||
| { readonly ok: false; readonly status: number; readonly detail: string };
|
||||
|
||||
/**
|
||||
* Persists validated upload bytes. Writes to `<id>.<ext>.part` first and
|
||||
* renames on success, so a crashed or aborted upload can never leave a file
|
||||
* that looks like a complete attachment. Re-running with the same token
|
||||
* overwrites atomically, which makes client retries safe.
|
||||
*/
|
||||
export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(function* (
|
||||
claims: AttachmentUploadClaims,
|
||||
bytes: Uint8Array,
|
||||
) {
|
||||
if (bytes.byteLength !== claims.sizeBytes) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 400,
|
||||
detail: `Body was ${bytes.byteLength} bytes, expected ${claims.sizeBytes}.`,
|
||||
} satisfies StoreUploadResult;
|
||||
}
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const extension = inferImageExtension({ mimeType: claims.mimeType });
|
||||
const relativePath = `${claims.attachmentId}${extension}`;
|
||||
const finalPath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
relativePath,
|
||||
});
|
||||
// Unique per request: two concurrent POSTs of the same token must not
|
||||
// interleave writes into one temp file. Both rename onto the final path
|
||||
// atomically; last one wins with identical claims-validated content.
|
||||
const partPath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: config.attachmentsDir,
|
||||
relativePath: `${relativePath}.${NodeCrypto.randomUUID()}.part`,
|
||||
});
|
||||
if (!finalPath || !partPath) {
|
||||
return { ok: false, status: 500, detail: "Failed to resolve attachment path." };
|
||||
}
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const writeResult = yield* Effect.gen(function* () {
|
||||
yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });
|
||||
yield* fileSystem.writeFile(partPath, bytes);
|
||||
yield* fileSystem.rename(partPath, finalPath);
|
||||
}).pipe(
|
||||
Effect.as({ ok: true } satisfies StoreUploadResult),
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to persist attachment upload.", {
|
||||
attachmentId: claims.attachmentId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(
|
||||
() =>
|
||||
({
|
||||
ok: false,
|
||||
status: 500,
|
||||
detail: "Failed to persist upload.",
|
||||
}) satisfies StoreUploadResult,
|
||||
),
|
||||
);
|
||||
return writeResult;
|
||||
});
|
||||
|
||||
/**
|
||||
* Deletes a never-sent upload. Idempotent, and refuses (as a silent no-op)
|
||||
* anything already claimed by a thread: those files are owned by their
|
||||
* message and only die with the thread.
|
||||
*/
|
||||
export const deletePendingAttachment = Effect.fn("AttachmentUpload.deletePending")(function* (
|
||||
attachmentId: string,
|
||||
) {
|
||||
if (parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
|
||||
return;
|
||||
}
|
||||
const uuid = parseAttachmentUuid(attachmentId);
|
||||
if (!uuid) return;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const filePath = findAttachmentPathByUuid({ attachmentsDir: config.attachmentsDir, uuid });
|
||||
if (!filePath) return;
|
||||
const path = yield* Path.Path;
|
||||
const foundId = parseAttachmentIdFromRelativePath(path.basename(filePath));
|
||||
if (
|
||||
!foundId ||
|
||||
parseThreadSegmentFromAttachmentId(foundId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(filePath).pipe(
|
||||
Effect.catch(
|
||||
() =>
|
||||
// Raced with the sweep or a duplicate delete; idempotent by design.
|
||||
Effect.void,
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -7,10 +7,19 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
createPendingAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
planAttachmentClaim,
|
||||
resolveAttachmentPathById,
|
||||
sweepStalePendingAttachments,
|
||||
toSafeThreadAttachmentSegment,
|
||||
PENDING_ATTACHMENT_MAX_AGE_MS,
|
||||
} from "./attachmentStore.ts";
|
||||
|
||||
function makeTempAttachmentsDir(): string {
|
||||
return NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"));
|
||||
}
|
||||
|
||||
describe("attachmentStore", () => {
|
||||
it("sanitizes thread ids when creating attachment ids", () => {
|
||||
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||
@@ -45,11 +54,9 @@ describe("attachmentStore", () => {
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
);
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const attachmentId = "thread-1-00000000-0000-4000-8000-00000000000a";
|
||||
const pngPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
|
||||
NodeFS.writeFileSync(pngPath, Buffer.from("hello"));
|
||||
|
||||
@@ -63,6 +70,155 @@ describe("attachmentStore", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves a pending id to the renamed thread-scoped file after claim", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const uuid = "00000000-0000-4000-8000-00000000000b";
|
||||
const scopedPath = NodePath.join(attachmentsDir, `thread-9-${uuid}.png`);
|
||||
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
|
||||
|
||||
// Old signed asset URLs carry the pending id; they must keep resolving.
|
||||
const resolved = resolveAttachmentPathById({
|
||||
attachmentsDir,
|
||||
attachmentId: `pending-${uuid}`,
|
||||
});
|
||||
expect(resolved).toBe(scopedPath);
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reserves the pending segment for uploads", () => {
|
||||
expect(toSafeThreadAttachmentSegment("pending")).toBe("pending_thread");
|
||||
const pendingId = createPendingAttachmentId();
|
||||
expect(parseThreadSegmentFromAttachmentId(pendingId)).toBe("pending");
|
||||
});
|
||||
|
||||
describe("planAttachmentClaim", () => {
|
||||
const uuid = "00000000-0000-4000-8000-00000000000c";
|
||||
|
||||
it("plans a rename for a pending attachment", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const pendingPath = NodePath.join(attachmentsDir, `pending-${uuid}.webp`);
|
||||
NodeFS.writeFileSync(pendingPath, Buffer.from("pixels"));
|
||||
|
||||
const claimPlan = planAttachmentClaim({
|
||||
attachmentsDir,
|
||||
threadId: "Thread.Foo",
|
||||
attachmentId: `pending-${uuid}`,
|
||||
});
|
||||
expect(claimPlan).toEqual({
|
||||
ok: true,
|
||||
finalId: `thread-foo-${uuid}`,
|
||||
currentPath: pendingPath,
|
||||
finalPath: NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`),
|
||||
alreadyScoped: false,
|
||||
});
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("is idempotent when a retry references an already-renamed file", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const scopedPath = NodePath.join(attachmentsDir, `thread-foo-${uuid}.webp`);
|
||||
NodeFS.writeFileSync(scopedPath, Buffer.from("pixels"));
|
||||
|
||||
const claimPlan = planAttachmentClaim({
|
||||
attachmentsDir,
|
||||
threadId: "Thread.Foo",
|
||||
attachmentId: `pending-${uuid}`,
|
||||
});
|
||||
expect(claimPlan).toMatchObject({ ok: true, alreadyScoped: true });
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses an attachment claimed by another thread", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(attachmentsDir, `other-thread-${uuid}.png`),
|
||||
Buffer.from("pixels"),
|
||||
);
|
||||
|
||||
const claimPlan = planAttachmentClaim({
|
||||
attachmentsDir,
|
||||
threadId: "Thread.Foo",
|
||||
attachmentId: `pending-${uuid}`,
|
||||
});
|
||||
expect(claimPlan).toMatchObject({ ok: false });
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a missing attachment", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const claimPlan = planAttachmentClaim({
|
||||
attachmentsDir,
|
||||
threadId: "Thread.Foo",
|
||||
attachmentId: `pending-${uuid}`,
|
||||
});
|
||||
expect(claimPlan).toMatchObject({ ok: false });
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sweepStalePendingAttachments", () => {
|
||||
it("deletes stale pending and partial files, keeps fresh and scoped ones", () => {
|
||||
const attachmentsDir = makeTempAttachmentsDir();
|
||||
try {
|
||||
const stalePending = NodePath.join(
|
||||
attachmentsDir,
|
||||
"pending-00000000-0000-4000-8000-000000000001.png",
|
||||
);
|
||||
const freshPending = NodePath.join(
|
||||
attachmentsDir,
|
||||
"pending-00000000-0000-4000-8000-000000000002.png",
|
||||
);
|
||||
const scoped = NodePath.join(
|
||||
attachmentsDir,
|
||||
"thread-1-00000000-0000-4000-8000-000000000003.png",
|
||||
);
|
||||
const stalePart = NodePath.join(
|
||||
attachmentsDir,
|
||||
"pending-00000000-0000-4000-8000-000000000004.png.part",
|
||||
);
|
||||
// Fixed epoch so the test never touches the real clock: files are
|
||||
// stamped relative to `nowMs` below, not to wall time.
|
||||
const nowMs = 1_800_000_000_000;
|
||||
const freshMs = nowMs - 60_000;
|
||||
const staleMs = nowMs - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
|
||||
for (const filePath of [stalePending, freshPending, scoped, stalePart]) {
|
||||
NodeFS.writeFileSync(filePath, Buffer.from("x"));
|
||||
}
|
||||
NodeFS.utimesSync(freshPending, freshMs / 1000, freshMs / 1000);
|
||||
NodeFS.utimesSync(stalePending, staleMs / 1000, staleMs / 1000);
|
||||
NodeFS.utimesSync(scoped, staleMs / 1000, staleMs / 1000);
|
||||
NodeFS.utimesSync(stalePart, staleMs / 1000, staleMs / 1000);
|
||||
|
||||
const swept = sweepStalePendingAttachments({
|
||||
attachmentsDir,
|
||||
nowMs,
|
||||
});
|
||||
expect(swept.deleted).toBe(2);
|
||||
expect(NodeFS.existsSync(stalePending)).toBe(false);
|
||||
expect(NodeFS.existsSync(stalePart)).toBe(false);
|
||||
expect(NodeFS.existsSync(freshPending)).toBe(true);
|
||||
expect(NodeFS.existsSync(scoped)).toBe(true);
|
||||
} finally {
|
||||
NodeFS.rmSync(attachmentsDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null when no attachment file exists for the id", () => {
|
||||
const attachmentsDir = NodeFS.mkdtempSync(
|
||||
NodePath.join(NodeOS.tmpdir(), "t3code-attachment-store-"),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
@@ -8,9 +9,8 @@ import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||
import { inferImageExtension } from "./imageMime.ts";
|
||||
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
@@ -19,6 +19,13 @@ const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||
"i",
|
||||
);
|
||||
|
||||
/**
|
||||
* Segment used for attachments uploaded before their thread exists
|
||||
* (upload-on-attach). Files named `pending-<uuid>.<ext>` are re-scoped to the
|
||||
* thread at turn start and swept when stale.
|
||||
*/
|
||||
export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
|
||||
|
||||
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = threadId
|
||||
.trim()
|
||||
@@ -31,9 +38,65 @@ export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
if (segment.length === 0) {
|
||||
return null;
|
||||
}
|
||||
// `pending` is reserved for not-yet-sent uploads; a thread that slugged to
|
||||
// it would have its attachments swept as orphans.
|
||||
if (segment === PENDING_ATTACHMENT_THREAD_SEGMENT) {
|
||||
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}_thread`;
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
export function createPendingAttachmentId(): string {
|
||||
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
/** Extracts the trailing uuid from a `<segment>-<uuid>` attachment id. */
|
||||
export function parseAttachmentUuid(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
|
||||
return match?.[2]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the on-disk file for an attachment uuid regardless of its current
|
||||
* segment (`pending-` before send, thread-scoped after). The uuid is the
|
||||
* stable identity: turn-start renames the file's segment but never the uuid,
|
||||
* which is what keeps send retries and signed asset URLs working across the
|
||||
* rename.
|
||||
*/
|
||||
export function findAttachmentPathByUuid(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly uuid: string;
|
||||
}): string | null {
|
||||
const uuid = input.uuid.toLowerCase();
|
||||
if (!new RegExp(`^${ATTACHMENT_ID_UUID_PATTERN}$`, "i").test(uuid)) {
|
||||
return null;
|
||||
}
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = NodeFS.readdirSync(input.attachmentsDir);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const suffixPattern = new RegExp(`-${uuid}\\.[a-z0-9]{1,8}$`, "i");
|
||||
for (const entry of entries) {
|
||||
if (!suffixPattern.test(entry)) {
|
||||
continue;
|
||||
}
|
||||
const resolved = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: entry,
|
||||
});
|
||||
if (resolved && NodeFS.existsSync(resolved)) {
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function createAttachmentId(threadId: string): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
@@ -80,20 +143,122 @@ export function resolveAttachmentPathById(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly attachmentId: string;
|
||||
}): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
// Resolution is by uuid, not by exact id: a signed asset URL minted for a
|
||||
// `pending-` id must keep working after turn start renames the file to its
|
||||
// thread segment (draft previews hold such URLs across a send).
|
||||
const uuid = parseAttachmentUuid(input.attachmentId);
|
||||
if (!uuid) {
|
||||
return null;
|
||||
}
|
||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||
const maybePath = resolveAttachmentRelativePath({
|
||||
return findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
|
||||
}
|
||||
|
||||
export type AttachmentClaimPlan =
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly finalId: string;
|
||||
readonly currentPath: string;
|
||||
readonly finalPath: string;
|
||||
/** True when a prior (possibly failed) send already renamed the file. */
|
||||
readonly alreadyScoped: boolean;
|
||||
}
|
||||
| { readonly ok: false; readonly reason: string };
|
||||
|
||||
/**
|
||||
* Plans the pending-to-thread re-scope for one referenced attachment at turn
|
||||
* start. Pure path logic; the caller performs the rename. The uuid is matched
|
||||
* against whatever segment the file currently has so retries after a partial
|
||||
* send are idempotent, and a file already claimed by a different thread is
|
||||
* refused rather than stolen.
|
||||
*/
|
||||
export function planAttachmentClaim(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly threadId: string;
|
||||
readonly attachmentId: string;
|
||||
}): AttachmentClaimPlan {
|
||||
const uuid = parseAttachmentUuid(input.attachmentId);
|
||||
if (!uuid) {
|
||||
return { ok: false, reason: "invalid attachment id" };
|
||||
}
|
||||
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
|
||||
if (!threadSegment) {
|
||||
return { ok: false, reason: "invalid thread id" };
|
||||
}
|
||||
const currentPath = findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });
|
||||
if (!currentPath) {
|
||||
return { ok: false, reason: "attachment not found (removed or expired)" };
|
||||
}
|
||||
const fileName = NodePath.basename(currentPath);
|
||||
const currentId = parseAttachmentIdFromRelativePath(fileName);
|
||||
const currentSegment = currentId ? parseThreadSegmentFromAttachmentId(currentId) : null;
|
||||
if (!currentSegment) {
|
||||
return { ok: false, reason: "attachment file name is malformed" };
|
||||
}
|
||||
const extension = NodePath.extname(fileName);
|
||||
const finalId = `${threadSegment}-${uuid}`;
|
||||
if (currentSegment === threadSegment) {
|
||||
return { ok: true, finalId, currentPath, finalPath: currentPath, alreadyScoped: true };
|
||||
}
|
||||
if (currentSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
|
||||
return { ok: false, reason: "attachment belongs to another thread" };
|
||||
}
|
||||
const finalPath = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${finalId}${extension}`,
|
||||
});
|
||||
if (!finalPath) {
|
||||
return { ok: false, reason: "failed to resolve attachment path" };
|
||||
}
|
||||
return { ok: true, finalId, currentPath, finalPath, alreadyScoped: false };
|
||||
}
|
||||
|
||||
export const PENDING_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
export const PARTIAL_UPLOAD_MAX_AGE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Deletes never-sent uploads (`pending-*`) past their retention window and
|
||||
* half-written `*.part` files left by aborted uploads. Runs at server start;
|
||||
* chip removal deletes eagerly, this is the backstop.
|
||||
*/
|
||||
export function sweepStalePendingAttachments(input: {
|
||||
readonly attachmentsDir: string;
|
||||
readonly nowMs: number;
|
||||
}): { readonly deleted: number } {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = NodeFS.readdirSync(input.attachmentsDir);
|
||||
} catch {
|
||||
return { deleted: 0 };
|
||||
}
|
||||
let deleted = 0;
|
||||
for (const entry of entries) {
|
||||
const isPartial = entry.endsWith(".part");
|
||||
const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
|
||||
if (!isPartial) {
|
||||
const id = parseAttachmentIdFromRelativePath(entry);
|
||||
const segment = id ? parseThreadSegmentFromAttachmentId(id) : null;
|
||||
if (segment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const resolved = resolveAttachmentRelativePath({
|
||||
attachmentsDir: input.attachmentsDir,
|
||||
relativePath: `${normalizedId}${extension}`,
|
||||
relativePath: entry,
|
||||
});
|
||||
if (maybePath && NodeFS.existsSync(maybePath)) {
|
||||
return maybePath;
|
||||
if (!resolved) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const stats = NodeFS.statSync(resolved);
|
||||
if (input.nowMs - stats.mtimeMs > maxAgeMs) {
|
||||
NodeFS.unlinkSync(resolved);
|
||||
deleted += 1;
|
||||
}
|
||||
} catch {
|
||||
// Raced with a concurrent delete or an unreadable entry; skip it.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return { deleted };
|
||||
}
|
||||
|
||||
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
|
||||
|
||||
@@ -83,6 +83,8 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -14,6 +15,8 @@ import * as LogLevel from "effect/LogLevel";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { sweepStalePendingAttachments } from "./attachmentStore.ts";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
|
||||
@@ -152,6 +155,18 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
// Backstop GC for upload-on-attach: never-sent `pending-*` uploads and
|
||||
// aborted `*.part` files. Eager deletes happen at chip removal; this covers
|
||||
// crashed clients and abandoned drafts.
|
||||
const nowMs = yield* Clock.currentTimeMillis;
|
||||
const swept = sweepStalePendingAttachments({
|
||||
attachmentsDir: derivedPaths.attachmentsDir,
|
||||
nowMs,
|
||||
});
|
||||
if (swept.deleted > 0) {
|
||||
yield* Effect.logInfo("Swept stale pending attachments.", { deleted: swept.deleted });
|
||||
}
|
||||
});
|
||||
|
||||
const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
|
||||
|
||||
@@ -28,6 +28,11 @@ import { OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
|
||||
import {
|
||||
ATTACHMENT_UPLOAD_ROUTE_PREFIX,
|
||||
storeAttachmentUpload,
|
||||
validateAttachmentUploadToken,
|
||||
} from "./assets/AttachmentUpload.ts";
|
||||
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
|
||||
@@ -226,6 +231,46 @@ export const assetRouteLayer = HttpRouter.add(
|
||||
}),
|
||||
);
|
||||
|
||||
export const attachmentUploadRouteLayer = HttpRouter.add(
|
||||
"POST",
|
||||
`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
|
||||
if (token.length === 0) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
// Invalid, tampered, and expired tokens are indistinguishable from
|
||||
// missing ones on purpose, matching the signed asset GET route.
|
||||
const claims = yield* validateAttachmentUploadToken(token);
|
||||
if (!claims) {
|
||||
return HttpServerResponse.text("Not Found", { status: 404 });
|
||||
}
|
||||
|
||||
const contentLength = Number(request.headers["content-length"] ?? "");
|
||||
if (!Number.isInteger(contentLength) || contentLength !== claims.sizeBytes) {
|
||||
return HttpServerResponse.text("Content-Length must match the minted upload size.", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const body = yield* request.arrayBuffer.pipe(Effect.orElseSucceed(() => null));
|
||||
if (body === null) {
|
||||
return HttpServerResponse.text("Failed to read the upload body.", { status: 400 });
|
||||
}
|
||||
|
||||
const stored = yield* storeAttachmentUpload(claims, new Uint8Array(body));
|
||||
return stored.ok
|
||||
? HttpServerResponse.empty({ status: 204 })
|
||||
: HttpServerResponse.text(stored.detail, { status: stored.status });
|
||||
}),
|
||||
);
|
||||
|
||||
export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
"GET",
|
||||
"*",
|
||||
|
||||
@@ -1,92 +1,20 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
import { inferImageExtension } from "./imageMime.ts";
|
||||
|
||||
describe("imageMime", () => {
|
||||
it("parses base64 data URL with mime type", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
it("maps known image mime types to extensions", () => {
|
||||
expect(inferImageExtension({ mimeType: "image/png" })).toBe(".png");
|
||||
expect(inferImageExtension({ mimeType: "image/jpeg" })).toBe(".jpg");
|
||||
expect(inferImageExtension({ mimeType: "IMAGE/WEBP" })).toBe(".webp");
|
||||
});
|
||||
|
||||
it("parses base64 data URL with mime parameters", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
it("falls back to a safe file name extension", () => {
|
||||
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.PNG" })).toBe(".png");
|
||||
});
|
||||
|
||||
it("rejects non-base64 data URL", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing mime type", () => {
|
||||
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses base64 data URL with spaces in payload", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects payload with characters outside the base64 alphabet", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects structurally malformed base64", () => {
|
||||
// '=' before the trailing padding position
|
||||
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
|
||||
// more than two padding characters
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
|
||||
// length not a multiple of 4
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts base64 with one or two trailing padding characters", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbA==",
|
||||
});
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8h",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty and whitespace-only payloads", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
|
||||
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses a case-insensitive scheme and mime type", () => {
|
||||
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses a multi-megabyte payload from a deep call stack", () => {
|
||||
// Regression: matching the payload with a regex borrowed the JS call
|
||||
// stack, so a ~10 MB image parsed inside fiber execution threw
|
||||
// "RangeError: Maximum call stack size exceeded".
|
||||
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
|
||||
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
|
||||
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
|
||||
const findMaxDepth = (depth: number): number => {
|
||||
try {
|
||||
return findMaxDepth(depth + 1);
|
||||
} catch {
|
||||
return depth;
|
||||
}
|
||||
};
|
||||
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
|
||||
expect(result?.mimeType).toBe("image/png");
|
||||
expect(result?.base64.length).toBe(14_000_000);
|
||||
it("falls back to .bin when nothing safe matches", () => {
|
||||
expect(inferImageExtension({ mimeType: "image/unknown", fileName: "shot.exe" })).toBe(".bin");
|
||||
});
|
||||
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
|
||||
@@ -29,89 +29,6 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".webp",
|
||||
]);
|
||||
|
||||
// Whether `code` is a character the base64 payload may contain, aside from
|
||||
// the whitespace handled separately below.
|
||||
function isBase64Char(code: number): boolean {
|
||||
return (
|
||||
(code >= 0x61 && code <= 0x7a) || // a-z
|
||||
(code >= 0x41 && code <= 0x5a) || // A-Z
|
||||
(code >= 0x30 && code <= 0x39) || // 0-9
|
||||
code === 0x2b || // +
|
||||
code === 0x2f || // /
|
||||
code === 0x3d // =
|
||||
);
|
||||
}
|
||||
|
||||
function isBase64Whitespace(code: number): boolean {
|
||||
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
|
||||
}
|
||||
|
||||
// Data URLs carry the full image payload, so this parser must never run a
|
||||
// regex across the payload: V8's regex engine borrows the JS call stack, and
|
||||
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
|
||||
// execution) throws "Maximum call stack size exceeded".
|
||||
export function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const trimmed = dataUrl.trim();
|
||||
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
|
||||
|
||||
const commaIndex = trimmed.indexOf(",");
|
||||
if (commaIndex === -1) return null;
|
||||
const header = trimmed.slice(5, commaIndex);
|
||||
if (header.length === 0) return null;
|
||||
|
||||
const headerParts: Array<string> = [];
|
||||
for (const part of header.split(";")) {
|
||||
const partTrimmed = part.trim();
|
||||
if (partTrimmed.length > 0) {
|
||||
headerParts.push(partTrimmed);
|
||||
}
|
||||
}
|
||||
if (headerParts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
const trailingToken = headerParts.at(-1)?.toLowerCase();
|
||||
if (trailingToken !== "base64") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mimeType = headerParts[0]?.toLowerCase();
|
||||
if (!mimeType) return null;
|
||||
|
||||
const payload = trimmed.slice(commaIndex + 1);
|
||||
const runs: Array<string> = [];
|
||||
let runStart = -1;
|
||||
for (let index = 0; index < payload.length; index += 1) {
|
||||
const code = payload.charCodeAt(index);
|
||||
if (isBase64Char(code)) {
|
||||
if (runStart === -1) runStart = index;
|
||||
continue;
|
||||
}
|
||||
if (!isBase64Whitespace(code)) return null;
|
||||
if (runStart !== -1) {
|
||||
runs.push(payload.slice(runStart, index));
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
if (runStart !== -1) {
|
||||
runs.push(payload.slice(runStart));
|
||||
}
|
||||
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
|
||||
if (base64.length === 0 || base64.length % 4 !== 0) return null;
|
||||
const firstPad = base64.indexOf("=");
|
||||
if (firstPad !== -1) {
|
||||
// '=' is only valid as one or two trailing padding characters; Node's
|
||||
// decoder would otherwise silently truncate at the first '='.
|
||||
if (base64.length - firstPad > 2) return null;
|
||||
for (let index = firstPad; index < base64.length; index += 1) {
|
||||
if (base64.charCodeAt(index) !== 0x3d) return null;
|
||||
}
|
||||
}
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const key = input.mimeType.toLowerCase();
|
||||
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import { normalizeDispatchCommand } from "./Normalizer.ts";
|
||||
|
||||
const testLayer = Layer.mergeAll(
|
||||
WorkspacePaths.layer,
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3-normalizer-attachments-" }),
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
const UUID = "00000000-0000-4000-8000-0000000000aa";
|
||||
|
||||
function turnStartCommand(attachment: {
|
||||
readonly id: string;
|
||||
readonly sizeBytes: number;
|
||||
}): ClientOrchestrationCommand {
|
||||
return {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("command-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-1"),
|
||||
role: "user",
|
||||
text: "look at this",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachment.id,
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
},
|
||||
],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: "2026-08-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("normalizeDispatchCommand attachments", () => {
|
||||
it.effect("claims a pending upload: renames the file and rewrites the id", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const bytes = Buffer.from("pixels");
|
||||
const pendingPath = NodePath.join(config.attachmentsDir, `pending-${UUID}.png`);
|
||||
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(pendingPath, bytes);
|
||||
|
||||
const normalized = yield* normalizeDispatchCommand(
|
||||
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
|
||||
);
|
||||
if (normalized.type !== "thread.turn.start") {
|
||||
throw new Error("Expected a thread.turn.start command");
|
||||
}
|
||||
expect(normalized.message.attachments).toHaveLength(1);
|
||||
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
|
||||
expect(NodeFS.existsSync(pendingPath)).toBe(false);
|
||||
expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`))).toBe(
|
||||
true,
|
||||
);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("is idempotent when a retry references an already-claimed file", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const bytes = Buffer.from("pixels");
|
||||
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `thread-1-${UUID}.png`), bytes);
|
||||
|
||||
// The retry still carries the original pending id.
|
||||
const normalized = yield* normalizeDispatchCommand(
|
||||
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
|
||||
);
|
||||
if (normalized.type !== "thread.turn.start") {
|
||||
throw new Error("Expected a thread.turn.start command");
|
||||
}
|
||||
expect(normalized.message.attachments[0]?.id).toBe(`thread-1-${UUID}`);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("fails when the referenced upload does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 6 }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toContain("not found");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("fails when the stored size does not match the reference", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(config.attachmentsDir, `pending-${UUID}.png`),
|
||||
Buffer.from("pixels"),
|
||||
);
|
||||
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: 999 }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toContain("size");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("refuses an attachment already claimed by another thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const bytes = Buffer.from("pixels");
|
||||
NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
|
||||
NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `other-thread-${UUID}.png`), bytes);
|
||||
|
||||
const error = yield* normalizeDispatchCommand(
|
||||
turnStartCommand({ id: `pending-${UUID}`, sizeBytes: bytes.byteLength }),
|
||||
).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationDispatchCommandError");
|
||||
expect(error.message).toContain("another thread");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,18 +1,15 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
type IsoDateTime,
|
||||
type OrchestrationCommand,
|
||||
OrchestrationDispatchCommandError,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
|
||||
import { planAttachmentClaim } from "../attachmentStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { parseBase64DataUrl } from "../imageMime.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
|
||||
export const canonicalizeClientCommandTimestamps = (
|
||||
@@ -48,7 +45,6 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
const receivedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
|
||||
@@ -104,67 +100,57 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
|
||||
return canonicalCommand as OrchestrationCommand;
|
||||
}
|
||||
|
||||
// Attachments arrive as id references to bytes already uploaded via the
|
||||
// signed upload URL flow. Each `pending-<uuid>` file is renamed to its
|
||||
// thread segment here; the uuid never changes, so signed asset URLs and
|
||||
// send retries (which may reference an already-renamed file) keep working.
|
||||
const normalizedAttachments = yield* Effect.forEach(
|
||||
canonicalCommand.message.attachments,
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (!parsed || !parsed.mimeType.startsWith("image/")) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Invalid image attachment payload for '${attachment.name}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(parsed.base64, "base64");
|
||||
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Image attachment '${attachment.name}' is empty or too large.`,
|
||||
});
|
||||
}
|
||||
|
||||
const attachmentId = createAttachmentId(canonicalCommand.threadId);
|
||||
if (!attachmentId) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: "Failed to create a safe attachment id.",
|
||||
});
|
||||
}
|
||||
|
||||
const persistedAttachment = {
|
||||
type: "image" as const,
|
||||
id: attachmentId,
|
||||
name: attachment.name,
|
||||
mimeType: parsed.mimeType.toLowerCase(),
|
||||
sizeBytes: bytes.byteLength,
|
||||
};
|
||||
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
const claimPlan = planAttachmentClaim({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment: persistedAttachment,
|
||||
threadId: canonicalCommand.threadId,
|
||||
attachmentId: attachment.id,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
if (!claimPlan.ok) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Failed to resolve persisted path for '${attachment.name}'.`,
|
||||
message: `Attachment '${attachment.name}' cannot be sent: ${claimPlan.reason}.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
|
||||
const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to create attachment directory for '${attachment.name}'.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to persist attachment '${attachment.name}'.`,
|
||||
message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (Number(stats.size) !== attachment.sizeBytes) {
|
||||
return yield* new OrchestrationDispatchCommandError({
|
||||
message: `Attachment '${attachment.name}' cannot be sent: stored size does not match the reference.`,
|
||||
});
|
||||
}
|
||||
|
||||
return persistedAttachment;
|
||||
if (!claimPlan.alreadyScoped) {
|
||||
yield* fileSystem.rename(claimPlan.currentPath, claimPlan.finalPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationDispatchCommandError({
|
||||
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...attachment,
|
||||
id: claimPlan.finalId,
|
||||
mimeType: attachment.mimeType.toLowerCase(),
|
||||
};
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as ServerConfig from "./config.ts";
|
||||
import {
|
||||
otlpTracesProxyRouteLayer,
|
||||
assetRouteLayer,
|
||||
attachmentUploadRouteLayer,
|
||||
serverEnvironmentHttpApiLayer,
|
||||
staticAndDevRouteLayer,
|
||||
browserApiCorsLayer,
|
||||
@@ -451,6 +452,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
),
|
||||
otlpTracesProxyRouteLayer,
|
||||
assetRouteLayer,
|
||||
attachmentUploadRouteLayer,
|
||||
staticAndDevRouteLayer,
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
|
||||
@@ -88,6 +88,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import { issueAssetUrl } from "./assets/AssetAccess.ts";
|
||||
import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -1839,6 +1840,16 @@ const makeWsRpcLayer = (
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.attachmentsCreateUploadUrl]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.attachmentsCreateUploadUrl, issueAttachmentUploadUrl(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.attachmentsDelete]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.attachmentsDelete,
|
||||
deletePendingAttachment(input.attachmentId),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsCreateUrl]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
|
||||
@@ -233,23 +233,6 @@ export interface PullRequestDialogState {
|
||||
key: number;
|
||||
}
|
||||
|
||||
export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(reader.result);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Could not read image data."));
|
||||
});
|
||||
reader.addEventListener("error", () => {
|
||||
reject(reader.error ?? new Error("Failed to read image."));
|
||||
});
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveSendEnvMode(input: {
|
||||
requestedEnvMode: DraftThreadEnvMode;
|
||||
isGitRepo: boolean;
|
||||
@@ -260,7 +243,7 @@ export function resolveSendEnvMode(input: {
|
||||
export function cloneComposerImageForRetry(
|
||||
image: ComposerImageAttachment,
|
||||
): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
if (!image.file || typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
}
|
||||
try {
|
||||
@@ -275,6 +258,7 @@ export function cloneComposerImageForRetry(
|
||||
|
||||
export function deriveComposerSendState(options: {
|
||||
prompt: string;
|
||||
/** Uploaded attachments only — an image still in flight is not sendable content. */
|
||||
imageCount: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
/**
|
||||
@@ -283,11 +267,17 @@ export function deriveComposerSendState(options: {
|
||||
* contexts do: a prompt of just element chips is still a valid send.
|
||||
*/
|
||||
elementContextCount?: number;
|
||||
/**
|
||||
* Why attachments are blocking the send (uploading or failed), or null.
|
||||
* Sending around an unsettled attachment would silently drop it.
|
||||
*/
|
||||
attachmentBlockReason?: string | null;
|
||||
}): {
|
||||
trimmedPrompt: string;
|
||||
sendableTerminalContexts: TerminalContextDraft[];
|
||||
expiredTerminalContextCount: number;
|
||||
hasSendableContent: boolean;
|
||||
attachmentBlockReason: string | null;
|
||||
} {
|
||||
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
|
||||
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
|
||||
@@ -303,6 +293,7 @@ export function deriveComposerSendState(options: {
|
||||
options.imageCount > 0 ||
|
||||
sendableTerminalContexts.length > 0 ||
|
||||
elementContextCount > 0,
|
||||
attachmentBlockReason: options.attachmentBlockReason ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -205,6 +205,8 @@ import {
|
||||
useComposerDraftStore,
|
||||
type DraftId,
|
||||
} from "../composerDraftStore";
|
||||
import { awaitAttachmentUploads, releaseComposerAttachment } from "../lib/attachmentUploadQueue";
|
||||
import { readyAttachmentRefs, summarizeAttachmentUploads } from "../lib/attachmentUploadState";
|
||||
import {
|
||||
appendTerminalContextsToPrompt,
|
||||
formatTerminalContextLabel,
|
||||
@@ -307,7 +309,6 @@ import {
|
||||
PullRequestDialogState,
|
||||
cloneComposerImageForRetry,
|
||||
deriveLockedProvider,
|
||||
readFileAsDataUrl,
|
||||
reconcileMountedTerminalThreadIds,
|
||||
resolveThreadMetadataUpdateForNextTurn,
|
||||
resolveSendEnvMode,
|
||||
@@ -4961,7 +4962,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
hasSendableContent,
|
||||
} = deriveComposerSendState({
|
||||
prompt: promptForSend,
|
||||
imageCount: composerImages.length,
|
||||
// Only uploaded attachments count: an image still in flight (or failed)
|
||||
// is not sendable content, and the composer blocks the send anyway.
|
||||
imageCount: summarizeAttachmentUploads(composerImages, environmentId).ready,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContextCount:
|
||||
composerElementContexts.length +
|
||||
@@ -4974,6 +4977,12 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
planMarkdown: activeProposedPlan.planMarkdown,
|
||||
});
|
||||
promptRef.current = "";
|
||||
// The follow-up sends text only; any attached images are being
|
||||
// discarded with the rest of the composer, so their uploads and
|
||||
// server-side bytes are released like a chip removal.
|
||||
for (const image of composerImages) {
|
||||
releaseComposerAttachment(image);
|
||||
}
|
||||
clearComposerDraftContent(composerDraftTarget);
|
||||
composerRef.current?.resetCursorState();
|
||||
await onSubmitPlanFollowUp({
|
||||
@@ -5086,15 +5095,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
effort: ctxSelectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
type: "image" as const,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
})),
|
||||
);
|
||||
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
||||
type: "image" as const,
|
||||
id: image.id,
|
||||
@@ -5206,13 +5206,26 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);
|
||||
if (failure === null && turnAttachmentsResult._tag === "Failure") {
|
||||
failure = turnAttachmentsResult;
|
||||
}
|
||||
// Attachments ride the turn as id references to bytes that uploaded the
|
||||
// moment they were attached. The composer blocks sending while an upload
|
||||
// is in flight, but the preview "pick and send" gesture attaches and sends
|
||||
// in one step, so wait for anything still running here.
|
||||
const settledUploads = await awaitAttachmentUploads(
|
||||
composerImagesSnapshot.map((image) => image.id),
|
||||
);
|
||||
const sendableImages = composerImagesSnapshot.map((image) => {
|
||||
const settledUpload = settledUploads.get(image.id);
|
||||
return settledUpload ? { ...image, upload: settledUpload } : image;
|
||||
});
|
||||
const turnAttachments = readyAttachmentRefs(sendableImages, environmentId);
|
||||
const unsentImageNames = sendableImages
|
||||
.filter(
|
||||
(image) => image.upload.status !== "ready" || image.upload.environmentId !== environmentId,
|
||||
)
|
||||
.map((image) => image.name);
|
||||
|
||||
let turnStartSucceeded = false;
|
||||
if (failure === null && turnAttachmentsResult._tag === "Success") {
|
||||
if (failure === null) {
|
||||
const bootstrap =
|
||||
isLocalDraftThread || baseBranchForWorktree
|
||||
? {
|
||||
@@ -5252,7 +5265,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
messageId: messageIdForSend,
|
||||
role: "user",
|
||||
text: outgoingMessageText,
|
||||
attachments: turnAttachmentsResult.value,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
modelSelection: ctxSelectedModelSelection,
|
||||
titleSeed: title,
|
||||
@@ -5267,6 +5280,15 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
} else {
|
||||
turnStartSucceeded = true;
|
||||
acknowledgeActiveThreadWoke();
|
||||
if (unsentImageNames.length > 0) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title: "Some images were not attached",
|
||||
description: `${unsentImageNames.join(", ")} did not finish uploading, so the message was sent without them.`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5290,7 +5312,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
promptRef.current = promptForSend;
|
||||
const retryComposerImages = composerImagesSnapshot.map(cloneComposerImageForRetry);
|
||||
// `sendableImages` carries the settled upload states; the pre-await
|
||||
// snapshot can still say `uploading` for a job that finished during
|
||||
// the await and would restore chips no live job will ever advance.
|
||||
const retryComposerImages = sendableImages.map(cloneComposerImageForRetry);
|
||||
composerImagesRef.current = retryComposerImages;
|
||||
composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
|
||||
composerElementContextsRef.current = composerElementContextsSnapshot;
|
||||
|
||||
@@ -176,6 +176,7 @@ import {
|
||||
type ComposerThreadDraftState,
|
||||
type DraftSessionState,
|
||||
} from "../composerDraftStore";
|
||||
import { releaseComposerAttachment } from "../lib/attachmentUploadQueue";
|
||||
|
||||
// Settled-tail paging: recent history is the common lookup; the deep tail
|
||||
// stays behind an explicit Show more.
|
||||
@@ -442,10 +443,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
|
||||
}) {
|
||||
const { composer, draftId, onDiscard, onNavigate, session } = props;
|
||||
const promptPreview = composer.prompt.trim().split("\n", 1)[0] ?? "";
|
||||
// images mirrors persistedAttachments once rehydration finishes; before
|
||||
// that only the persisted list is populated, hence max not sum.
|
||||
const attachmentCount =
|
||||
Math.max(composer.images.length, composer.persistedAttachments.length) +
|
||||
composer.images.length +
|
||||
composer.terminalContexts.length +
|
||||
composer.elementContexts.length +
|
||||
composer.previewAnnotations.length +
|
||||
@@ -611,6 +610,14 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
|
||||
]);
|
||||
const handleDiscard = useCallback(
|
||||
(draftId: DraftId) => {
|
||||
// Discarding the draft abandons its attachments: stop in-flight
|
||||
// uploads and free the server-side bytes before the store forgets
|
||||
// them. (Server-side, only never-sent `pending-` files can be
|
||||
// deleted, so this can never touch a sent thread's attachments.)
|
||||
const draftImages = useComposerDraftStore.getState().getComposerDraft(draftId)?.images ?? [];
|
||||
for (const image of draftImages) {
|
||||
releaseComposerAttachment(image);
|
||||
}
|
||||
// The /draft/$draftId route redirects home on its own when the draft
|
||||
// it renders disappears, so discarding the open draft needs no
|
||||
// special-casing here.
|
||||
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
replaceTextRange,
|
||||
shouldSubmitComposerOnEnter,
|
||||
} from "../../composer-logic";
|
||||
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
|
||||
import { deriveComposerSendState } from "../ChatView.logic";
|
||||
import {
|
||||
dataTransferHasComposerMention,
|
||||
makeComposerMentionDragHandlers,
|
||||
@@ -57,13 +57,27 @@ import {
|
||||
} from "../../composerDraftStore";
|
||||
import {
|
||||
MAX_STASH_ENTRIES,
|
||||
partitionStashAttachments,
|
||||
usePromptStashStore,
|
||||
type PromptStashEntry,
|
||||
} from "../../promptStashStore";
|
||||
import { ComposerStashBadge } from "./ComposerStashBadge";
|
||||
import { ComposerStashMenu } from "./ComposerStashMenu";
|
||||
import { compressImageForStash, compressImageToByteLimit } from "../../lib/imageCompression";
|
||||
import { compressImageToByteLimit } from "../../lib/imageCompression";
|
||||
import {
|
||||
cancelAttachmentUpload,
|
||||
releaseComposerAttachment,
|
||||
retryAttachmentUpload,
|
||||
startAttachmentUpload,
|
||||
} from "../../lib/attachmentUploadQueue";
|
||||
import {
|
||||
ATTACHMENT_WRONG_ENVIRONMENT_REASON,
|
||||
attachmentUploadBlockReason,
|
||||
formatAttachmentUploadProgress,
|
||||
isAttachmentInWrongEnvironment,
|
||||
resolveAttachmentEnvironmentAction,
|
||||
summarizeAttachmentUploads,
|
||||
} from "../../lib/attachmentUploadState";
|
||||
import { useAssetUrls } from "~/assets/assetUrls";
|
||||
import { isCommandPaletteOpen } from "../../commandPaletteBus";
|
||||
import { getTerminalFocusOwner } from "../../lib/terminalFocus";
|
||||
import { resolveShortcutCommand } from "../../keybindings";
|
||||
@@ -666,7 +680,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setThreadError,
|
||||
onExpandImage,
|
||||
} = props;
|
||||
const isSendDisabled = sendDisabledReason !== null;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Store subscriptions (prompt / images / terminal contexts)
|
||||
@@ -678,12 +691,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerElementContexts = composerDraft.elementContexts;
|
||||
const composerPreviewAnnotations = composerDraft.previewAnnotations;
|
||||
const composerReviewComments = composerDraft.reviewComments;
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
|
||||
const setComposerDraftImageUpload = useComposerDraftStore((store) => store.setImageUpload);
|
||||
const insertComposerDraftTerminalContext = useComposerDraftStore(
|
||||
(store) => store.insertTerminalContext,
|
||||
);
|
||||
@@ -702,16 +715,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const removeComposerDraftReviewComment = useComposerDraftStore(
|
||||
(store) => store.removeReviewComment,
|
||||
);
|
||||
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.clearPersistedAttachments,
|
||||
);
|
||||
const clearComposerDraftPromptAndImages = useComposerDraftStore(
|
||||
(store) => store.clearComposerPromptAndImages,
|
||||
);
|
||||
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.syncPersistedAttachments,
|
||||
);
|
||||
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Model state
|
||||
@@ -974,12 +980,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const dragDepthRef = useRef(0);
|
||||
const stashPulseKeyRef = useRef(0);
|
||||
const stashPulseTimeoutRef = useRef<number | null>(null);
|
||||
/**
|
||||
* Snapshots currently being encoded, keyed by target+prompt+image ids.
|
||||
* Keyed rather than boolean so a genuinely different prompt (or a different
|
||||
* thread) can still be stashed while an earlier encode is running.
|
||||
*/
|
||||
const stashInFlightRef = useRef<Set<string>>(new Set());
|
||||
/**
|
||||
* Count of pasted images still being compressed, per thread. Reserved
|
||||
* against the attachment limit so concurrent pastes can't overshoot it,
|
||||
@@ -991,26 +991,35 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// ------------------------------------------------------------------
|
||||
// Derived: composer send state
|
||||
// ------------------------------------------------------------------
|
||||
const attachmentUploadSummary = useMemo(
|
||||
() => summarizeAttachmentUploads(composerImages, environmentId),
|
||||
[composerImages, environmentId],
|
||||
);
|
||||
const composerSendState = useMemo(
|
||||
() =>
|
||||
deriveComposerSendState({
|
||||
prompt,
|
||||
imageCount: composerImages.length,
|
||||
imageCount: attachmentUploadSummary.ready,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContextCount:
|
||||
composerElementContexts.length +
|
||||
composerPreviewAnnotations.length +
|
||||
composerReviewComments.length,
|
||||
attachmentBlockReason: attachmentUploadBlockReason(attachmentUploadSummary),
|
||||
}),
|
||||
[
|
||||
attachmentUploadSummary,
|
||||
composerElementContexts.length,
|
||||
composerImages.length,
|
||||
composerPreviewAnnotations.length,
|
||||
composerReviewComments.length,
|
||||
composerTerminalContexts,
|
||||
prompt,
|
||||
],
|
||||
);
|
||||
// An unsettled attachment blocks the send just like a loading thread does:
|
||||
// sending around it would silently drop an image the user can see attached.
|
||||
const effectiveSendDisabledReason = sendDisabledReason ?? composerSendState.attachmentBlockReason;
|
||||
const isSendDisabled = effectiveSendDisabledReason !== null;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Derived: composer trigger / menu
|
||||
@@ -1128,9 +1137,48 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerMenuItemsRef.current = composerMenuItems;
|
||||
activeComposerMenuItemRef.current = activeComposerMenuItem;
|
||||
|
||||
const nonPersistedComposerImageIdSet = useMemo(
|
||||
() => new Set(nonPersistedComposerImageIds),
|
||||
[nonPersistedComposerImageIds],
|
||||
// Attachments restored from a persisted draft have no blob preview: their
|
||||
// bytes only exist on the server, so the thumbnail comes from a signed
|
||||
// asset URL — the same flow sent-message attachments already use.
|
||||
const restoredAttachmentIds = useMemo(
|
||||
() =>
|
||||
composerImages.flatMap((image) =>
|
||||
image.previewUrl.length === 0 && image.upload.status === "ready"
|
||||
? [image.upload.attachmentId]
|
||||
: [],
|
||||
),
|
||||
[composerImages],
|
||||
);
|
||||
const restoredAttachmentResources = useMemo(
|
||||
() =>
|
||||
restoredAttachmentIds.map((attachmentId) => ({
|
||||
_tag: "attachment" as const,
|
||||
attachmentId,
|
||||
})),
|
||||
[restoredAttachmentIds],
|
||||
);
|
||||
const restoredAttachmentUrls = useAssetUrls(environmentId, restoredAttachmentResources);
|
||||
const restoredAttachmentUrlById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
restoredAttachmentIds.flatMap((attachmentId, index) => {
|
||||
const url = restoredAttachmentUrls[index];
|
||||
return url ? [[attachmentId, url] as const] : [];
|
||||
}),
|
||||
),
|
||||
[restoredAttachmentIds, restoredAttachmentUrls],
|
||||
);
|
||||
/** Chips as rendered: local blob preview when we have one, signed URL otherwise. */
|
||||
const displayComposerImages = useMemo(
|
||||
() =>
|
||||
composerImages.map((image) => {
|
||||
if (image.previewUrl.length > 0 || image.upload.status !== "ready") {
|
||||
return image;
|
||||
}
|
||||
const previewUrl = restoredAttachmentUrlById.get(image.upload.attachmentId);
|
||||
return previewUrl ? { ...image, previewUrl } : image;
|
||||
}),
|
||||
[composerImages, restoredAttachmentUrlById],
|
||||
);
|
||||
|
||||
const isComposerApprovalState = activePendingApproval !== null;
|
||||
@@ -1450,72 +1498,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Image persist effect
|
||||
// Attachment environment retargeting
|
||||
// ------------------------------------------------------------------
|
||||
// The bytes live in exactly one environment. When a draft is pointed at a
|
||||
// different one, an attachment we still hold the File for is silently
|
||||
// re-uploaded; the old environment's copy is released only after the new
|
||||
// upload lands (`supersedes`), so a failed re-upload never destroys the
|
||||
// only server copy. One restored after a reload has no File to re-send;
|
||||
// its ready state is left intact and the mismatch is rendered and
|
||||
// send-gated as a derived condition, so switching back recovers it.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
if (composerImages.length === 0) {
|
||||
clearComposerDraftPersistedAttachments(composerDraftTarget);
|
||||
return;
|
||||
}
|
||||
const getPersistedAttachmentsForThread = () =>
|
||||
getComposerDraft(composerDraftTarget)?.persistedAttachments ?? [];
|
||||
try {
|
||||
const currentPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
const existingPersistedById = new Map(
|
||||
currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),
|
||||
);
|
||||
const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();
|
||||
await Promise.all(
|
||||
composerImages.map(async (image) => {
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(image.file);
|
||||
stagedAttachmentById.set(image.id, {
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl,
|
||||
});
|
||||
} catch {
|
||||
const existingPersisted = existingPersistedById.get(image.id);
|
||||
if (existingPersisted) {
|
||||
stagedAttachmentById.set(image.id, existingPersisted);
|
||||
for (const image of composerImages) {
|
||||
if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") {
|
||||
const previousUpload = image.upload;
|
||||
cancelAttachmentUpload(image.id);
|
||||
startAttachmentUpload({
|
||||
target: composerDraftTarget,
|
||||
environmentId,
|
||||
image,
|
||||
...(previousUpload.status === "ready"
|
||||
? {
|
||||
supersedes: {
|
||||
environmentId: previousUpload.environmentId,
|
||||
attachmentId: previousUpload.attachmentId,
|
||||
},
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serialized = Array.from(stagedAttachmentById.values());
|
||||
if (cancelled) return;
|
||||
syncComposerDraftPersistedAttachments(composerDraftTarget, serialized);
|
||||
} catch {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
const fallbackPersistedIds: Array<string> = [];
|
||||
for (const attachment of fallbackPersistedAttachments) {
|
||||
if (currentImageIds.has(attachment.id)) {
|
||||
fallbackPersistedIds.push(attachment.id);
|
||||
}
|
||||
}
|
||||
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
|
||||
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
|
||||
fallbackPersistedIdSet.has(attachment.id),
|
||||
);
|
||||
if (cancelled) return;
|
||||
syncComposerDraftPersistedAttachments(composerDraftTarget, fallbackAttachments);
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [
|
||||
composerDraftTarget,
|
||||
clearComposerDraftPersistedAttachments,
|
||||
composerImages,
|
||||
getComposerDraft,
|
||||
syncComposerDraftPersistedAttachments,
|
||||
]);
|
||||
}
|
||||
}, [composerDraftTarget, composerImages, environmentId]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Callbacks: prompt change
|
||||
@@ -1910,7 +1922,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const stashQueue = usePromptStashStore((state) => state.entries);
|
||||
const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
|
||||
const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
|
||||
const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1967,7 +1978,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
}
|
||||
|
||||
let unrestoredImageNames: string[] = [];
|
||||
if (entry.attachments.length > 0) {
|
||||
// Attachment bytes live in one environment. Restoring into a different
|
||||
// one cannot reach them, so those come back as named drops.
|
||||
const wrongEnvironmentImageNames = entry.attachments
|
||||
.filter((attachment) => attachment.environmentId !== environmentId)
|
||||
.map((attachment) => attachment.name);
|
||||
const restorableAttachments = entry.attachments.filter(
|
||||
(attachment) => attachment.environmentId === environmentId,
|
||||
);
|
||||
if (restorableAttachments.length > 0) {
|
||||
const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
|
||||
// The draft store also dedupes by mimeType+sizeBytes+name, so filter
|
||||
// on the same key here. Counting a duplicate against capacity would
|
||||
@@ -1982,7 +2001,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
0,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - composerImagesRef.current.length,
|
||||
);
|
||||
const pending = entry.attachments.filter(
|
||||
const pending = restorableAttachments.filter(
|
||||
(attachment) =>
|
||||
!existingIds.has(attachment.id) &&
|
||||
!existingDedupKeys.has(
|
||||
@@ -2003,18 +2022,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// prompt across threads and providers, so whatever the composer has
|
||||
// selected right now stays selected.
|
||||
|
||||
// Each cause gets its own sentence so "too large" is never blamed for a
|
||||
// file that actually failed to decode, or for one the composer simply
|
||||
// had no room to take back.
|
||||
// Each cause gets its own sentence so "still uploading" is never blamed
|
||||
// for a file that actually failed, or for one the composer simply had no
|
||||
// room to take back.
|
||||
const missingImageReasons: string[] = [];
|
||||
if (entry.droppedImageNames.length > 0) {
|
||||
missingImageReasons.push(
|
||||
`${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`,
|
||||
`${entry.droppedImageNames.join(", ")} had not finished uploading when this prompt was saved.`,
|
||||
);
|
||||
}
|
||||
if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) {
|
||||
missingImageReasons.push(
|
||||
`${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`,
|
||||
`${entry.unreadableImageNames.join(", ")} failed to upload when this prompt was saved.`,
|
||||
);
|
||||
}
|
||||
if (wrongEnvironmentImageNames.length > 0) {
|
||||
missingImageReasons.push(
|
||||
`${wrongEnvironmentImageNames.join(", ")} is not available in this environment.`,
|
||||
);
|
||||
}
|
||||
if (unrestoredImageNames.length > 0) {
|
||||
@@ -2042,6 +2066,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
addComposerDraftImages,
|
||||
composerDraftTarget,
|
||||
composerImagesRef,
|
||||
environmentId,
|
||||
promptRef,
|
||||
setComposerDraftPrompt,
|
||||
takeStashEntry,
|
||||
@@ -2064,7 +2089,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
[takeStashEntry],
|
||||
);
|
||||
|
||||
const stashCurrentPrompt = useCallback(async () => {
|
||||
const stashCurrentPrompt = useCallback(() => {
|
||||
// Terminal-context placeholders reference live sessions the stash can't
|
||||
// round-trip, so they are stripped from the stashed prompt.
|
||||
const prompt = promptRef.current.split(INLINE_TERMINAL_CONTEXT_PLACEHOLDER).join("").trim();
|
||||
@@ -2073,149 +2098,111 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setIsStashMenuOpen((open) => !open);
|
||||
return;
|
||||
}
|
||||
// A repeat ⌘S on the *same* still-unencoded snapshot would stash it
|
||||
// twice. Guard on the snapshot itself rather than a bare boolean: once
|
||||
// the composer has been cleared the user can type something genuinely
|
||||
// new (or switch threads) while encoding continues, and that deserves its
|
||||
// own entry.
|
||||
const snapshotKey = `${String(composerDraftTarget)} | ||||