Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(chat): send persisted attachment refs with retried messages

Steven Enamakel674989486ba1
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index c34615f322..d96d5e7831 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -1317,6 +1317,8 @@ const Conversations = ({
// Originals ride beside the text as typed parts; the core stages them.
const attachmentParts = attachmentsToParts(pendingAttachments);
let messageText = trimmed;
+ let persistedMessageId: string | undefined;
+ let persistedAttachmentParts: ContentPart[] = [];
const userMessage: ThreadMessage = {
id: `msg_${globalThis.crypto.randomUUID()}`,
content: messageText,
@@ -1351,6 +1353,8 @@ const Conversations = ({
if (retryingUnchangedMessage) {
// The core already has this exact prompt from the failed attempt.
messageText = previousFailedMessage.content;
+ persistedMessageId = previousFailedMessage.id;
+ persistedAttachmentParts = previousFailedMessage.attachments ?? [];
} else if (previousFailedMessage) {
// A corrected retry must replace the already-persisted failed prompt;
// appending it would leave both prompts in the transcript. The edit
@@ -1387,6 +1391,8 @@ const Conversations = ({
).unwrap();
// The core saved the originals before returning this durable reference.
messageText = persisted.message.content;
+ persistedMessageId = persisted.message.id;
+ persistedAttachmentParts = persisted.message.attachments ?? [];
persistedFailedMessageByThreadRef.current.set(sendingThreadId, persisted.message);
}
} catch (error) {
@@ -1436,7 +1442,15 @@ const Conversations = ({
await chatSend({
threadId: sendingThreadId,
message: messageText,
- ...(opts?.voicePart ? { attachments: [opts.voicePart] } : {}),
+ ...(persistedAttachmentParts.length || opts?.voicePart
+ ? {
+ persistedMessageId,
+ attachments: [
+ ...persistedAttachmentParts,
+ ...(opts?.voicePart ? [opts.voicePart] : []),
+ ],
+ }
+ : {}),
...(modelOverride !== undefined ? { model: modelOverride } : {}),
locale: uiLocale,
reasoningEffort: composerReasoningEffort,
diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts
index 5fe1bdc3f9..73d7ec52cf 100644
--- a/app/src/services/chatService.ts
+++ b/app/src/services/chatService.ts
@@ -896,6 +896,8 @@ type QueueMode = 'interrupt' | 'steer' | 'followup' | 'collect' | 'parallel';
interface ChatSendParams {
threadId: string;
message: string;
+ /** Persisted user row that owns the opaque `attachments` refs. */
+ persistedMessageId?: string;
/**
* Typed attachments (`image`/`video`/`file` parts with an inline `data:` URI)
* sent beside `message`; the core stages them. Never splice upload markers
@@ -964,6 +966,7 @@ export async function chatSend(params: ChatSendParams): Promise<string | undefin
client_id: clientId,
thread_id: params.threadId,
message: params.message,
+ persisted_message_id: params.persistedMessageId ?? undefined,
attachments: params.attachments?.length ? params.attachments : undefined,
model_override: params.model ?? undefined,
locale: params.locale ?? undefined,
diff --git a/crates/openhuman-core/src/web_chat/schemas.rs b/crates/openhuman-core/src/web_chat/schemas.rs
index 093ea0dd49..9c3a6072e6 100644
--- a/crates/openhuman-core/src/web_chat/schemas.rs
+++ b/crates/openhuman-core/src/web_chat/schemas.rs
@@ -76,9 +76,13 @@ pub fn schemas(function: &str) -> ControllerSchema {
FieldSchema {
name: "attachments",
ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment: "Typed attachments (tinychannels ContentPart[]). VoiceNote parts carry an opaque id for audio already stored by channel.web_voice_note_store; the core validates and binds it to the user row without adding audio markers to model text. Other media parts use the regular attachment staging path.",
+ comment: "Typed attachments (tinychannels ContentPart[]). VoiceNote parts carry an opaque id validated by channel.web_voice_note_store. Other media parts must be opaque refs returned on the persisted user message; their stored bytes are resolved under the trusted turn scope.",
required: false,
},
+ optional_string(
+ "persisted_message_id",
+ "User message row that owns the opaque typed attachment refs.",
+ ),
optional_string("model_override", "Optional model override."),
optional_f64("temperature", "Optional temperature override."),
optional_string(
diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rs
index c60fc2a4da..5716a6a65e 100644
--- a/crates/openhuman-core/src/web_chat/types.rs
+++ b/crates/openhuman-core/src/web_chat/types.rs
@@ -78,11 +78,13 @@ pub(crate) struct WebChatParams {
pub(super) client_id: String,
pub(super) thread_id: String,
pub(super) message: String,
- /// Typed attachments sent with `message`; ordinary media is folded into
- /// upload markers at the RPC edge, while voice notes retain their typed
- /// opaque reference and stay out of model-visible text.
+ /// Typed media refs returned for a previously persisted user row. The
+ /// trusted runner resolves these refs against that exact row at execution.
#[serde(default)]
pub(super) attachments: Vec<tinychannels_bus::ContentPart>,
+ /// Persisted user message whose opaque attachment refs accompany this turn.
+ #[serde(default)]
+ pub(super) persisted_message_id: Option<String>,
pub(super) model_override: Option<String>,
pub(super) temperature: Option<f64>,
/// BCP-47 locale of the frontend UI (e.g. `ar`, `zh-CN`). When set
diff --git a/scripts/debug/web-scripts/typed-image-attachment-roundtrip.mjs b/scripts/debug/web-scripts/typed-image-attachment-roundtrip.mjs
index 3be2716d87..5166b24cc7 100644
--- a/scripts/debug/web-scripts/typed-image-attachment-roundtrip.mjs
+++ b/scripts/debug/web-scripts/typed-image-attachment-roundtrip.mjs
@@ -1,4 +1,4 @@
-import { readFileSync } from "node:fs";
+import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
const USER_TEXT = "Describe the attached image briefly.";
@@ -16,6 +16,21 @@ function unwrap(value) {
return value;
}
+function findStoredBytes(root, expected) {
+ for (const name of readdirSync(root)) {
+ const path = join(root, name);
+ const stat = statSync(path);
+ if (stat.isDirectory()) {
+ const found = findStoredBytes(path, expected);
+ if (found) return found;
+ } else if (stat.isFile() && stat.size === expected.length) {
+ const bytes = readFileSync(path);
+ if (bytes.equals(expected)) return bytes;
+ }
+ }
+ return null;
+}
+
export default async function typedImageAttachmentRoundtrip({
page,
mock,
@@ -107,48 +122,63 @@ export default async function typedImageAttachmentRoundtrip({
);
const persisted = stagedMessage?.messages?.find(
(message) =>
- message.sender === "user" && message.content.includes(FILE_NAME),
+ message.sender === "user" && message.id === append.params?.message?.id,
);
if (!persisted)
throw new Error("typed image was not persisted in the thread message list");
- if (/\[(?:IMAGE|FILE):/i.test(persisted.content))
+ if (/\[(?:ATTACHMENT|IMAGE|FILE):/i.test(persisted.content))
throw new Error(
- "modern typed upload leaked a legacy [IMAGE:]/[FILE:] marker",
+ "modern typed upload leaked a staging marker into new persisted content",
);
- const encoded = persisted.content.match(/\[ATTACHMENT:([^\]]+)\]/)?.[1];
- if (!encoded)
- throw new Error("persisted message has no durable attachment reference");
- const reference = JSON.parse(decodeURIComponent(encoded));
+ const reference = persisted.attachments?.[0];
if (
- reference.name !== FILE_NAME ||
- reference.mime !== "image/png" ||
- reference.size_bytes !== IMAGE_BYTES.length ||
- !reference.path.startsWith("uploads/")
+ reference?.kind !== "image" ||
+ reference.media?.contentType !== "image/png" ||
+ reference.media?.fileName !== FILE_NAME ||
+ reference.media?.sizeBytes !== IMAGE_BYTES.length ||
+ !reference.media?.opaqueId ||
+ reference.media?.path ||
+ reference.media?.url
) {
throw new Error(
- `staged reference lost image metadata: ${JSON.stringify(reference)}`,
+ `persisted image reference is not opaque and typed: ${JSON.stringify(reference)}`,
);
}
- const stagedBytes = readFileSync(join(logDir, "workspace", reference.path));
- if (!stagedBytes.equals(IMAGE_BYTES))
+ if (persisted.content !== USER_TEXT)
+ throw new Error("persisted user text differs from clean composer text");
+ const stagedBytes = findStoredBytes(join(logDir, "workspace"), IMAGE_BYTES);
+ if (!stagedBytes)
throw new Error("staged image bytes differ from the browser upload");
log(
- `core staged ${reference.mime} ${reference.name} (${stagedBytes.length} bytes) at ${reference.path}`,
+ `core staged ${reference.media.contentType} ${reference.media.fileName} (${stagedBytes.length} bytes) behind opaque ref ${reference.media.opaqueId}`,
);
const chatRequest = rpcCalls.find(
(call) => call.method === "openhuman.channel_web_chat",
);
- if (!chatRequest || chatRequest.params?.message !== persisted.content)
+ if (
+ !chatRequest ||
+ chatRequest.params?.message !== persisted.content ||
+ chatRequest.params?.persisted_message_id !== persisted.id
+ )
throw new Error(
- "chat turn did not reuse the staged durable reference as its message",
+ "chat turn did not reference the marker-free persisted user row",
);
- if (/\[(?:IMAGE|FILE):/i.test(chatRequest.params.message))
- throw new Error("chat turn sent a legacy attachment marker");
- if (chatRequest.params?.attachments?.length)
+ if (/\[(?:ATTACHMENT|IMAGE|FILE):/i.test(chatRequest.params.message))
throw new Error(
- "ordinary attachment was staged twice as a chat part and durable reference",
+ "chat turn sent a staging marker in its modern user text",
);
+ if (
+ JSON.stringify(chatRequest.params?.attachments) !==
+ JSON.stringify(persisted.attachments)
+ )
+ throw new Error("chat turn did not carry the persisted opaque media ref");
+ if (
+ JSON.stringify(chatRequest.params.attachments).match(
+ /data:|base64|"(?:path|url)"\s*:/i,
+ )
+ )
+ throw new Error("chat turn sent source bytes or a filesystem/network path");
const inferenceRequest = mock
.requests()
@@ -193,10 +223,24 @@ export default async function typedImageAttachmentRoundtrip({
message.content.includes("typed-roundtrip.png"),
)?.content;
}, threadId);
+ const restoredMessage = await page.evaluate((id) => {
+ const messages =
+ window.__OPENHUMAN_STORE__?.getState?.().thread?.messagesByThreadId?.[
+ id
+ ] ?? [];
+ return messages.find(
+ (message) => message.sender === "user" && message.id === id,
+ );
+ }, threadId);
if (restored !== persisted.content)
throw new Error(
- "reloaded conversation did not restore the durable image reference",
+ "reloaded conversation did not restore the marker-free user text",
);
+ if (
+ JSON.stringify(restoredMessage?.attachments) !==
+ JSON.stringify(persisted.attachments)
+ )
+ throw new Error("reloaded conversation did not restore the opaque image ref");
log(
"typed image attachment survived core staging, chat submission and reload",
);