fix(composer): read dropped threads across environments (#15210)

This commit is contained in:
Bilal Bakr authored and GitHub committed 2026-10-14 21:58:12 -05:00
1 parent ec1313c8f8
commit 55dfc5fc4d
21 files changed
+1164 -108

No files matched your search

+182 -104
View File
@@ -43,6 +43,7 @@ import type {
SnapShotSource,
} from "@t3tools/contracts";
import {
EnvironmentRequestInvalidError,
AuthOrchestrationOperateScope,
ProviderDriverKind,
ProviderInstanceId,
@@ -52,6 +53,8 @@ import {
PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
} from "@t3tools/contracts";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Schema from "effect/Schema";
import {
isPasteAsTextShortcut,
nextPastedTextFileName,
@@ -68,6 +71,7 @@ import {
type ReactNode,
useCallback,
useEffect,
useEffectEvent,
useId,
useImperativeHandle,
useLayoutEffect,
@@ -247,7 +251,7 @@ import {
threadContextReference,
} from "~/lib/composerContextRecords";
import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems";
import { THREAD_CONTEXT_DROP_EVENT, threadContextDropTargetProps } from "./threadContextDrag";
import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";
import { readThreadShell, useThreadShells } from "~/state/entities";
import { requestConfirmDialog } from "~/confirmDialog";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
@@ -260,6 +264,8 @@ import { resolveAssetUrl } from "~/assets/assetUrls";
import { assetEnvironment } from "~/state/assets";
import { readPreparedConnection } from "~/state/session";
import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
import { orchestrationEnvironment } from "~/state/orchestration";
import { threadContextAttachment } from "~/lib/threadContextAttachment";
import {
pullRequestEnvironment,
usePullRequestList,
@@ -338,6 +344,10 @@ import {
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
import { PierreEntryIcon } from "./PierreEntryIcon";
import { pendingDraftWork } from "./pendingDraftWork";
import {
importComposerThreadAttachment,
remainingComposerAttachmentSlots,
} from "./composerThreadImport";
import { isTimelineScrollTarget } from "./timelineScrollTarget";
import {
createComposerScrollGestureState,
@@ -419,6 +429,7 @@ function SnapShotAttachmentFrame({
}
const COMPOSER_PULL_REQUEST_LIST_LIMIT = 99;
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
const COMPOSER_PULL_REQUEST_RESULT_LIMIT = 12;
const EMPTY_PULL_REQUEST_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> =
[];
@@ -2535,6 +2546,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
* the next draft.
*/
const pendingImageCompressionsRef = useRef<Map<string, number>>(new Map());
const pendingThreadImportsRef = useRef<Map<string, number>>(new Map());
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
isRevertingCheckpointRef.current = isRevertingCheckpoint;
@@ -3231,6 +3243,41 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
],
);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, {
reportFailure: false,
});
const countReservedAttachments = useCallback(() => {
const questionRequest = pendingUserInputs[0];
const otherQuestionKeys =
questionAttachmentTarget && questionRequest && activeThreadId
? questionRequest.questions
.map((question) =>
questionAttachmentDraftId(
environmentId,
activeThreadId,
questionRequest.requestId,
question.id,
),
)
.filter((key) => key !== questionAttachmentTarget)
: [];
const draft = getComposerDraft(attachmentDraftTarget);
return (
(draft?.images.length ?? 0) +
(draft?.files.length ?? 0) +
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
(pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) +
countQuestionAttachments(otherQuestionKeys)
);
}, [
activeThreadId,
attachmentDraftTarget,
attachmentTargetKey,
environmentId,
getComposerDraft,
pendingUserInputs,
questionAttachmentTarget,
]);
/**
* Bytes for a pasted image or file come back through the source environment's asset URL
* (the client is the only party that can reach both) and re-enter this draft as a normal
@@ -3281,6 +3328,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// The draft these bytes belong to may have been sent or switched away from while they
// downloaded. Dropping them here keeps them out of whatever draft is open now.
if (attachmentTargetKeyRef.current !== importTargetKey) return;
const replacesFileMarker =
record.kind === "file" &&
composerFilesRef.current.some(
(candidate) =>
composerFileNeedsReattach(candidate) &&
composerFileMatchesReattachMarker(candidate, {
name: record.name,
mimeType: file.type,
sizeBytes: file.size,
}),
);
if (
!replacesFileMarker &&
(pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
) {
fail("The attachment limit has been reached.");
return;
}
if (record.kind === "image") {
const accepted = addComposerImage({
type: "image",
@@ -3308,7 +3374,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
fail("The draft rejected this attachment (duplicate or attachment limit reached).");
}
},
[addComposerFilesToDraft, addComposerImage, attachmentTargetKey, createAssetUrl],
[
addComposerFilesToDraft,
addComposerImage,
composerFilesRef,
countReservedAttachments,
createAssetUrl,
],
);
const importAttachmentRecord = useCallback(
async (
@@ -4308,7 +4380,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
event?.preventDefault();
toastManager.add({
type: "info",
title: "Still bringing a pasted attachment into this message.",
title: "Still bringing attached context into this message.",
description: "Send again once its chip resolves.",
});
return;
@@ -4796,11 +4868,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
appendedFiles.push(restored);
}
const capacity = Math.max(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS -
composerImagesRef.current.length -
composerFilesNow.length,
const capacity = remainingComposerAttachmentSlots(
composerImagesRef.current.length + composerFilesNow.length,
pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
);
// Marker replacements reuse their marker's slot; only appended files
// consume capacity.
@@ -4855,12 +4925,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
(image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
),
);
const capacity = Math.max(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS -
composerImagesRef.current.length -
composerFilesRef.current.length -
restoredFileCount,
const capacity = remainingComposerAttachmentSlots(
composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
);
const pending = entry.attachments.filter(
(attachment) =>
@@ -4977,7 +5044,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
toastManager.add({
type: "info",
title: "Still bringing a pasted attachment into this message.",
title: "Still bringing attached context into this message.",
description: "Stash again once its chip resolves.",
});
return;
@@ -5814,28 +5881,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Callbacks: attachments
// ------------------------------------------------------------------
const countReservedAttachments = () => {
const questionRequest = pendingUserInputs[0];
const otherQuestionKeys =
questionAttachmentTarget && questionRequest && activeThreadId
? questionRequest.questions
.map((question) =>
questionAttachmentDraftId(
environmentId,
activeThreadId,
questionRequest.requestId,
question.id,
),
)
.filter((key) => key !== questionAttachmentTarget)
: [];
return (
composerImagesRef.current.length +
composerFilesRef.current.length +
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
countQuestionAttachments(otherQuestionKeys)
);
};
/** Resolves true when at least one chip was inserted for the accepted attachments. */
const addComposerAttachments = async (
files: File[],
@@ -6320,78 +6365,110 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
},
});
// Sidebar thread drops arrive as a DOM event on the form (see threadContextDrag.ts).
useEffect(() => {
const form = composerFormRef.current;
if (!form) return;
const onThreadDrop = (event: Event) => {
const refs = (event as CustomEvent<ReadonlyArray<ScopedThreadRef>>).detail;
if (refs.some((ref) => ref.environmentId !== environmentId)) {
const attachDroppedThreadFile = useEffectEvent((file: File) => addComposerAttachments([file]));
const importDroppedThread = useEffectEvent(
async (ref: ScopedThreadRef, isActive: () => boolean) => {
const targetKey = attachmentTargetKey;
pendingDraftWork.begin(targetKey);
const loadingToast = toastManager.add({
type: "loading",
title: "Loading thread context…",
timeout: 0,
data: { threadRef: routeThreadRef, hideCopyButton: true },
});
try {
await importComposerThreadAttachment({
targetKey,
pendingImports: pendingThreadImportsRef.current,
countReservedAttachments,
load: async () => {
const result = await loadThreadTranscript({
environmentId: ref.environmentId,
input: { threadId: ref.threadId },
});
if (result._tag !== "Success") {
throw squashAtomCommandFailure(result);
}
return threadContextAttachment(ref.environmentId, result.value);
},
isActive,
attach: attachDroppedThreadFile,
onLimitReached: () => {
if (activeThreadId) {
setThreadError(
activeThreadId,
`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
);
}
},
});
} catch (error) {
if (!isActive()) return;
toastManager.add({
type: "error",
title: "Use threads from this environment",
description: "The agent can only read threads on its own server.",
title: "Unable to read the dropped thread",
description:
isEnvironmentRequestInvalidError(error) &&
error.reason === "thread_transcript_too_large"
? "This thread exceeds the attachment size limit. Try a shorter thread."
: "Check that its environment is connected and up to date, then try again.",
});
} finally {
toastManager.close(loadingToast);
pendingDraftWork.end(targetKey);
}
},
);
useThreadContextDrop(composerFormRef, environmentId, attachmentTargetKey, (refs, isActive) => {
const records = refs.flatMap((ref) => {
if (ref.environmentId !== environmentId) {
void importDroppedThread(
ref,
() => isActive() && attachmentTargetKeyRef.current === attachmentTargetKey,
);
return [];
}
const shell = readThreadShell(ref);
return shell ? [threadContextRecord(ref, shell.title)] : [];
});
if (records.length === 0) return;
if (questionAttachmentTarget !== null) {
const canAnswer =
canOperateThread &&
!isConnecting &&
!isComposerApprovalState &&
!activePendingIsResponding &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false;
const text = `${records
.map((record) => formatInlineContextReference(threadContextReference(record)))
.join(" ")} `;
const snapshot = readComposerSnapshot();
const cursor = snapshot.expandedCursor;
const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? "");
const inserted =
canAnswer &&
applyPromptReplacement(
cursor,
extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text),
leadingSpace ? ` ${text}` : text,
);
if (!inserted) {
toastManager.add({
type: "error",
title: "Unable to add thread",
description: "The composer is busy; try again once it is ready.",
});
return;
}
const records = refs.flatMap((ref) => {
const shell = readThreadShell(ref);
return shell ? [threadContextRecord(ref, shell.title)] : [];
addComposerDraftThreadContexts(questionAttachmentTarget, records, {
appendReference: false,
});
if (records.length === 0) return;
if (questionAttachmentTarget !== null) {
const canAnswer =
canOperateThread &&
!isConnecting &&
!isComposerApprovalState &&
!activePendingIsResponding &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false;
const text = `${records
.map((record) => formatInlineContextReference(threadContextReference(record)))
.join(" ")} `;
const snapshot = readComposerSnapshot();
const cursor = snapshot.expandedCursor;
const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? "");
const inserted =
canAnswer &&
applyPromptReplacement(
cursor,
extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text),
leadingSpace ? ` ${text}` : text,
);
if (!inserted) {
toastManager.add({
type: "error",
title: "Unable to add thread",
description: "The composer is busy; try again once it is ready.",
});
return;
}
addComposerDraftThreadContexts(questionAttachmentTarget, records, {
appendReference: false,
});
if (isComposerCollapsedMobile) expandMobileComposer();
} else {
addComposerDraftThreadContexts(composerDraftTarget, records);
}
};
form.addEventListener(THREAD_CONTEXT_DROP_EVENT, onThreadDrop);
return () => form.removeEventListener(THREAD_CONTEXT_DROP_EVENT, onThreadDrop);
}, [
activePendingIsResponding,
activePendingProgress?.activeQuestion?.allowCustomAnswer,
addComposerDraftThreadContexts,
applyPromptReplacement,
canOperateThread,
composerDraftTarget,
environmentId,
expandMobileComposer,
isComposerApprovalState,
isComposerCollapsedMobile,
isConnecting,
questionAttachmentTarget,
readComposerSnapshot,
]);
if (isComposerCollapsedMobile) expandMobileComposer();
} else {
addComposerDraftThreadContexts(composerDraftTarget, records);
}
});
const onComposerMentionDragLeaveCapture = (event: React.DragEvent<HTMLFormElement>) => {
if (!dataTransferHasComposerMention(event.dataTransfer.types)) return;
@@ -6540,7 +6617,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusComposer();
},
hasPendingAttachments: () =>
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0,
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0 ||
pendingDraftWork.has(attachmentTargetKey),
insertTextAtEnd: insertComposerTextAtEnd,
pasteTextAtEnd: (text: string, options) => {
const bypassAutoAttachment =
@@ -0,0 +1,308 @@
import { EnvironmentId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
import { act, createElement, useRef } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { describe, expect, it, vi } from "vite-plus/test";
import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
import {
importComposerThreadAttachment,
remainingComposerAttachmentSlots,
} from "./composerThreadImport";
import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag";
function deferredFile() {
let resolve!: (file: File) => void;
let reject!: (error: Error) => void;
const promise = new Promise<File>((resolveFile, rejectFile) => {
resolve = resolveFile;
reject = rejectFile;
});
return { promise, resolve, reject };
}
describe("importComposerThreadAttachment", () => {
it.each(["expand", "draft switch", "environment switch", "unmount"])(
"keeps import ownership correct after %s while loading",
async (change) => {
const target = new EventTarget();
const transcript = deferredFile();
const pendingImports = new Map<string, number>();
const attached: string[] = [];
const expandedAtDrop: boolean[] = [];
let importing!: Promise<void>;
function Composer({
environmentId,
targetKey,
expanded,
}: {
environmentId: EnvironmentId;
targetKey: string;
expanded: boolean;
}) {
const targetRef = useRef<EventTarget | null>(target);
useThreadContextDrop(targetRef, environmentId, targetKey, (_refs, isActive) => {
expandedAtDrop.push(expanded);
importing = importComposerThreadAttachment({
targetKey,
pendingImports,
countReservedAttachments: () => pendingImports.get(targetKey) ?? 0,
load: () => transcript.promise,
isActive,
attach: async (file) => {
attached.push(file.name);
return true;
},
onLimitReached: () => {
throw new Error("The slot should be available");
},
});
});
return null;
}
const props = {
environmentId: EnvironmentId.make("destination"),
targetKey: "draft",
expanded: false,
};
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
let renderer: ReactTestRenderer | undefined;
try {
act(() => {
renderer = create(createElement(Composer, props));
});
act(() => target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })));
expect(pendingImports.get("draft")).toBe(1);
if (change === "unmount") {
act(() => renderer?.unmount());
} else {
act(() =>
renderer?.update(
createElement(Composer, {
...props,
expanded: true,
...(change === "draft switch" ? { targetKey: "another-draft" } : {}),
...(change === "environment switch"
? { environmentId: EnvironmentId.make("another-environment") }
: {}),
}),
),
);
if (change !== "expand") {
act(() => renderer?.update(createElement(Composer, props)));
}
}
transcript.resolve(new File(["transcript"], "thread.txt"));
await act(async () => importing);
expect(attached).toEqual(change === "expand" ? ["thread.txt"] : []);
expect(pendingImports.size).toBe(0);
if (change === "expand") {
act(() =>
target.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [] })),
);
await act(async () => importing);
expect(expandedAtDrop).toEqual([false, true]);
expect(attached).toEqual(["thread.txt", "thread.txt"]);
}
} finally {
act(() => renderer?.unmount());
vi.unstubAllGlobals();
}
},
);
it("rejects the next drop before loading when the draft takes the final slot", async () => {
const targetKey = DraftId.make("thread-import-synchronous-admission");
const store = useComposerDraftStore.getState();
const pendingImports = new Map<string, number>();
const files = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) => ({
type: "file" as const,
id: `existing-${index}`,
name: `existing-${index}.txt`,
mimeType: "text/plain",
sizeBytes: 1,
file: new File(["x"], `existing-${index}.txt`, { type: "text/plain" }),
}));
store.addFiles(targetKey, files);
const load = vi.fn(async () => new File(["transcript"], "thread.jsonl"));
const onLimitReached = vi.fn();
const input = {
targetKey,
pendingImports,
countReservedAttachments: () =>
(store.getComposerDraft(targetKey)?.files.length ?? 0) +
(pendingImports.get(targetKey) ?? 0),
load,
isActive: () => true,
attach: async (file: File) =>
store.addFiles(targetKey, [
{
type: "file",
id: "transcript",
name: file.name,
mimeType: file.type,
sizeBytes: file.size,
file,
},
]).length > 0,
onLimitReached,
};
await importComposerThreadAttachment(input);
await importComposerThreadAttachment(input);
expect(load).toHaveBeenCalledTimes(1);
expect(onLimitReached).toHaveBeenCalledTimes(1);
expect(store.getComposerDraft(targetKey)?.files.at(-1)?.name).toBe("thread.jsonl");
expect(pendingImports.size).toBe(0);
store.clearComposerContent(targetKey);
});
it.each(["file", "image"])(
"reserves the final slot while restoring a stashed %s",
async (kind) => {
const pendingImports = new Map<string, number>();
const targetKey = "draft";
const attached = Array.from(
{ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 },
(_, index) => `existing-${index}`,
);
const countReservedAttachments = () => attached.length + (pendingImports.get(targetKey) ?? 0);
const attach = async (file: File) => {
if (
remainingComposerAttachmentSlots(attached.length, pendingImports.get(targetKey) ?? 0) ===
0
) {
return false;
}
attached.push(file.name);
return true;
};
const transcript = deferredFile();
const importing = importComposerThreadAttachment({
targetKey,
pendingImports,
countReservedAttachments,
load: () => transcript.promise,
isActive: () => true,
attach,
onLimitReached: () => {
throw new Error("The final slot should be available");
},
});
expect(await attach(new File(["unrelated"], `unrelated.${kind}`))).toBe(false);
transcript.resolve(new File(["transcript"], "thread.txt"));
await importing;
expect(attached.at(-1)).toBe("thread.txt");
expect(attached).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS);
expect(pendingImports.size).toBe(0);
},
);
it("rejects a repeated drop until the reserved slot is released", async () => {
const pendingImports = new Map<string, number>();
const transcript = deferredFile();
const load = vi.fn(() => transcript.promise);
const onLimitReached = vi.fn();
const attach = vi.fn(async (_file: File) => true);
const input = {
targetKey: "draft",
pendingImports,
countReservedAttachments: () =>
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 + (pendingImports.get("draft") ?? 0),
load,
isActive: () => true,
attach,
onLimitReached,
};
const first = importComposerThreadAttachment(input);
await importComposerThreadAttachment(input);
expect(load).toHaveBeenCalledTimes(1);
expect(onLimitReached).toHaveBeenCalledTimes(1);
transcript.resolve(new File(["transcript"], "thread.txt"));
await first;
await importComposerThreadAttachment(input);
expect(attach).toHaveBeenCalledTimes(2);
expect(pendingImports.size).toBe(0);
});
it("keeps the second drop's slot reserved when the first drop finishes", async () => {
const pendingImports = new Map<string, number>();
const first = deferredFile();
const second = deferredFile();
const attached: string[] = [];
const countReservedAttachments = () =>
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 2 + attached.length + (pendingImports.get("draft") ?? 0);
const attach = async (file: File) => {
if (countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) return false;
attached.push(file.name);
return true;
};
const input = {
targetKey: "draft",
pendingImports,
countReservedAttachments,
isActive: () => true,
attach,
onLimitReached: () => {
throw new Error("Both slots should be available");
},
};
const firstImport = importComposerThreadAttachment({ ...input, load: () => first.promise });
const secondImport = importComposerThreadAttachment({ ...input, load: () => second.promise });
first.resolve(new File(["first"], "first-thread.txt"));
await firstImport;
expect(await attach(new File(["unrelated"], "unrelated.txt"))).toBe(false);
second.resolve(new File(["second"], "second-thread.txt"));
await secondImport;
expect(attached).toEqual(["first-thread.txt", "second-thread.txt"]);
expect(pendingImports.size).toBe(0);
});
it.each(["failure", "inactive"])(
"releases the original draft's slot after %s",
async (outcome) => {
const pendingImports = new Map<string, number>();
const transcript = deferredFile();
const attach = vi.fn(async (_file: File) => true);
let activeTargetKey = "original-draft";
const input = {
targetKey: "original-draft",
pendingImports,
countReservedAttachments: () =>
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 + (pendingImports.get("original-draft") ?? 0),
load: () => transcript.promise,
isActive: () => activeTargetKey === "original-draft",
attach,
onLimitReached: () => {
throw new Error("The slot should have been released");
},
};
const importing = importComposerThreadAttachment(input);
if (outcome === "inactive") activeTargetKey = "new-draft";
expect(pendingImports.get("new-draft") ?? 0).toBe(0);
if (outcome === "failure") {
const failed = expect(importing).rejects.toThrow("Failed to load");
transcript.reject(new Error("Failed to load"));
await failed;
} else {
transcript.resolve(new File(["transcript"], "stale-thread.txt"));
await importing;
}
expect(attach).not.toHaveBeenCalled();
expect(pendingImports.size).toBe(0);
await importComposerThreadAttachment({
...input,
load: async () => new File(["transcript"], "retry-thread.txt"),
isActive: () => true,
});
expect(attach.mock.calls[0]?.[0]?.name).toBe("retry-thread.txt");
expect(pendingImports.size).toBe(0);
},
);
});
@@ -0,0 +1,40 @@
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
export function remainingComposerAttachmentSlots(
attachmentCount: number,
pendingThreadImports: number,
) {
return Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - attachmentCount - pendingThreadImports);
}
export async function importComposerThreadAttachment(input: {
readonly targetKey: string;
readonly pendingImports: Map<string, number>;
readonly countReservedAttachments: () => number;
readonly load: () => Promise<File>;
readonly isActive: () => boolean;
readonly attach: (file: File) => Promise<boolean>;
readonly onLimitReached: () => void;
}): Promise<void> {
if (input.countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
input.onLimitReached();
return;
}
input.pendingImports.set(input.targetKey, (input.pendingImports.get(input.targetKey) ?? 0) + 1);
let reserved = true;
const release = () => {
if (!reserved) return;
reserved = false;
const remaining = (input.pendingImports.get(input.targetKey) ?? 0) - 1;
if (remaining > 0) input.pendingImports.set(input.targetKey, remaining);
else input.pendingImports.delete(input.targetKey);
};
try {
const file = await input.load();
if (!input.isActive()) return;
release();
await input.attach(file);
} finally {
release();
}
}
@@ -1,5 +1,5 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useSyncExternalStore } from "react";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { type RefObject, useEffect, useEffectEvent, useSyncExternalStore } from "react";
/**
* Dragging a sidebar thread past the list edge turns the sort gesture into a context drop.
@@ -10,6 +10,28 @@ import { useSyncExternalStore } from "react";
*/
export const THREAD_CONTEXT_DROP_EVENT = "t3-thread-context-drop";
export function useThreadContextDrop(
targetRef: RefObject<EventTarget | null>,
environmentId: EnvironmentId,
targetKey: string,
onDrop: (refs: ReadonlyArray<ScopedThreadRef>, isActive: () => boolean) => void,
) {
const handleDrop = useEffectEvent(onDrop);
useEffect(() => {
const target = targetRef.current;
if (!target) return;
let active = true;
const listener = (event: Event) =>
handleDrop((event as CustomEvent<ReadonlyArray<ScopedThreadRef>>).detail, () => active);
target.addEventListener(THREAD_CONTEXT_DROP_EVENT, listener);
return () => {
active = false;
target.removeEventListener(THREAD_CONTEXT_DROP_EVENT, listener);
};
}, [environmentId, targetKey, targetRef]);
}
const DROP_TARGET_ATTRIBUTE = "data-thread-context-drop";
const DROP_OVER_ATTRIBUTE = "data-thread-context-over";