Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: attachments reach the new engine, office files as their text

ogsamrat606e5ee056e0
diff --git a/apps/app/src/app/lib/opencode-v2-adapter.ts b/apps/app/src/app/lib/opencode-v2-adapter.ts
index 574eaeb8..cf92c065 100644
--- a/apps/app/src/app/lib/opencode-v2-adapter.ts
+++ b/apps/app/src/app/lib/opencode-v2-adapter.ts
@@ -1659,11 +1659,18 @@ export function createClientV2(
.filter((part) => part.type === "text" && typeof part.text === "string")
.map((part) => typeof part.text === "string" ? part.text : "")
.join("");
+ // Attachments go as the engine's files (a data: or file: URI each); the server turns office files into text.
+ const files = (parameters.parts ?? []).flatMap((part) => {
+ const file = part as { type?: string; url?: unknown; filename?: unknown };
+ return file.type === "file" && typeof file.url === "string" && file.url
+ ? [{ uri: file.url, name: typeof file.filename === "string" && file.filename ? file.filename : "attachment" }]
+ : [];
+ });
const promptResult = await request(
"POST",
`/api/session/${encodeURIComponent(parameters.sessionID)}/prompt`,
// The UI's id becomes the saved user message, so an uncertain send can be checked by id.
- { text, ...(parameters.messageID?.startsWith("msg_") ? { id: parameters.messageID } : {}) },
+ { text, ...(files.length ? { files } : {}), ...(parameters.messageID?.startsWith("msg_") ? { id: parameters.messageID } : {}) },
options?.signal,
);
return promptResult.response.ok ? successfulResult(promptResult, {}) : failedResult(promptResult);
diff --git a/apps/app/tests/opencode-v2-adapter.test.ts b/apps/app/tests/opencode-v2-adapter.test.ts
index b781653e..09ecac5e 100644
--- a/apps/app/tests/opencode-v2-adapter.test.ts
+++ b/apps/app/tests/opencode-v2-adapter.test.ts
@@ -1454,6 +1454,27 @@ describe("OpenCode v2 client compatibility", () => {
}
});
+ test("sends attachments as the engine's files", async () => {
+ const originalFetch = globalThis.fetch;
+ let sent: unknown = null;
+ globalThis.fetch = async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ if (request.url.endsWith("/prompt")) sent = await request.json();
+ return jsonResponse({ data: {} });
+ };
+ try {
+ const client = createClientV2("http://opencode.test/opencode2", "/workspace", {});
+ await client.session.promptAsync({
+ sessionID: "ses_files",
+ model: { providerID: "omnirush", modelID: "gpt-6-astra" },
+ parts: [{ type: "text", text: "look" }, { type: "file", mime: "image/png", url: "data:image/png;base64,AA==", filename: "a.png" } as never],
+ });
+ expect(sent).toEqual({ text: "look", files: [{ uri: "data:image/png;base64,AA==", name: "a.png" }] });
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
test.each(["model", "prompt"])("propagates network rejection from %s without fabricating success", async (endpoint) => {
const originalFetch = globalThis.fetch;
const failure = new TypeError("network unavailable");
diff --git a/apps/server/src/engine-v2-attachments.ts b/apps/server/src/engine-v2-attachments.ts
new file mode 100644
index 00000000..0684b8e3
--- /dev/null
+++ b/apps/server/src/engine-v2-attachments.ts
@@ -0,0 +1,47 @@
+/**
+ * Office attachments (docx, xlsx, pptx) on the 2.x engine. The engine reads a text or image attachment itself but
+ * drops these silently, so a prompt's office files become the same text the 1.x engine's office plugin produced
+ * (opencode-plugins/omnirush-office-attachments.ts, loaded from where the app ships it): user content added to the
+ * prompt, the file's exact bytes kept in the project's inbox as before.
+ */
+import { pathToFileURL } from "node:url";
+
+import { omnirushPluginPath } from "./omnirush-extensions-plugin-path.js";
+
+type PromptFile = { uri?: unknown; name?: unknown; description?: unknown };
+type OfficePlugin = (input: { directory: string }) => Promise<{
+ "experimental.chat.messages.transform": (input: unknown, output: { messages: unknown[] }) => Promise<void>;
+}>;
+
+const OFFICE = /\.(docx|xlsx|pptx)$/i;
+const OFFICE_MIME = /officedocument\.(wordprocessingml\.document|spreadsheetml\.sheet|presentationml\.presentation)/i;
+
+let plugin: Promise<OfficePlugin> | undefined;
+const officePlugin = () => (plugin ??= import(pathToFileURL(omnirushPluginPath("omnirush-office-attachments")).href)
+ .then((module: { OmniRushOfficeAttachments: OfficePlugin }) => module.OmniRushOfficeAttachments));
+
+function isOffice(file: PromptFile): boolean {
+ const name = typeof file.name === "string" ? file.name : "";
+ const uri = typeof file.uri === "string" ? file.uri : "";
+ return OFFICE.test(name) || OFFICE.test(uri.split("?")[0] ?? "") || OFFICE_MIME.test(uri.slice(0, 120));
+}
+
+/** The prompt body with its office files turned into text; the body as it was when it has none. */
+export async function convertOfficeAttachments(body: Record<string, unknown>, root: string): Promise<Record<string, unknown>> {
+ const files = Array.isArray(body.files) ? (body.files as PromptFile[]) : [];
+ const office = files.filter(isOffice);
+ if (office.length === 0) return body;
+ const parts = office.map((file) => ({
+ type: "file", url: file.uri, filename: typeof file.name === "string" ? file.name : "attachment",
+ }));
+ const output = { messages: [{ info: { role: "user" }, parts }] };
+ await (await (await officePlugin())({ directory: root }))["experimental.chat.messages.transform"]({}, output);
+ const converted = (output.messages[0] as { parts?: Array<{ type?: string; text?: string }> }).parts ?? [];
+ const texts = converted.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text as string);
+ const rest = files.filter((file) => !isOffice(file));
+ const text = [typeof body.text === "string" ? body.text : "", ...texts].filter(Boolean).join("\n\n");
+ const next: Record<string, unknown> = { ...body, text };
+ if (rest.length) next.files = rest;
+ else delete next.files;
+ return next;
+}
diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.ts
index 50ac9421..525e9821 100644
--- a/apps/server/src/engine-v2-next.test.ts
+++ b/apps/server/src/engine-v2-next.test.ts
@@ -174,3 +174,35 @@ test("the quota wrap on the 2.x engine: asked only while idle, an accepted offer
expect(asked).toEqual(["ses_b:offer"]);
expect(compacted).toEqual(["ses_a"]);
});
+
+test("office attachments reach the 2.x engine as their text; other files stay files", () => withDir(async (dir) => {
+ const { convertOfficeAttachments } = await import("./engine-v2-attachments.js");
+ const made = Bun.spawnSync(["python3", "-c", `
+import zipfile, sys
+d = sys.argv[1]
+zipfile.ZipFile(d + "/doc.docx", "w").writestr("word/document.xml", "<w:document><w:body><w:t>DOCX-4711</w:t></w:body></w:document>")
+zipfile.ZipFile(d + "/deck.pptx", "w").writestr("ppt/slides/slide1.xml", "<p:sld><a:t>PPTX-4712</a:t></p:sld>")
+z = zipfile.ZipFile(d + "/book.xlsx", "w")
+z.writestr("xl/workbook.xml", '<workbook xmlns:r="r"><sheets><sheet name="S" sheetId="1" r:id="rId1"/></sheets></workbook>')
+z.writestr("xl/_rels/workbook.xml.rels", '<Relationships><Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>')
+z.writestr("xl/sharedStrings.xml", "<sst><si><t>XLSX-4713</t></si></sst>")
+z.writestr("xl/worksheets/sheet1.xml", '<worksheet><sheetData><row r="1"><c r="A1" t="s"><v>0</v></c></row></sheetData></worksheet>')
+z.close()
+`, dir]);
+ if (made.exitCode !== 0) return;
+ const docx = `data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,${(await Bun.file(join(dir, "doc.docx")).bytes()).toBase64()}`;
+ const body = await convertOfficeAttachments({
+ text: "read these",
+ files: [
+ { uri: docx, name: "doc.docx" },
+ { uri: `file://${join(dir, "deck.pptx")}`, name: "deck.pptx" },
+ { uri: `file://${join(dir, "book.xlsx")}`, name: "book.xlsx" },
+ { uri: "data:text/plain;base64,aGk=", name: "note.txt" },
+ ],
+ }, dir);
+ expect(String(body.text)).toStartWith("read these");
+ for (const sentinel of ["DOCX-4711", "PPTX-4712", "XLSX-4713"]) expect(String(body.text)).toContain(sentinel);
+ expect(body.files).toEqual([{ uri: "data:text/plain;base64,aGk=", name: "note.txt" }]);
+ const plain = { text: "no office", files: [{ uri: "data:image/png;base64,AA==", name: "a.png" }] };
+ expect(await convertOfficeAttachments(plain, dir)).toBe(plain);
+}));
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 0188c86b..f808c6b6 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -234,6 +234,7 @@ import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provide
import { createEngineV2Preview, resolveInitialEngineV2PreviewState, type EngineV2Preview } from "./engine-v2-preview.js";
import { MIGRATED_FROM } from "./engine-v2-migration.js";
import { createV2BudgetWrap } from "./engine-v2-budget-wrap.js";
+import { convertOfficeAttachments } from "./engine-v2-attachments.js";
import { createEditorLsp, LSP_OPS, type LspOp, type LspPayload } from "./editor-lsp.js";
import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";
import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";
@@ -2228,6 +2229,19 @@ export async function proxyOpencodeV2Request(input: {
headers.delete("content-length");
headers.set("content-type", "application/json");
}
+ if (method === "POST" && /^\/api\/session\/[^/]+\/prompt$/.test(routePath) && requestBody) {
+ // Office files the engine would drop go in as their text (engine-v2-attachments.ts).
+ let promptInput: unknown = null;
+ try { promptInput = JSON.parse(new TextDecoder().decode(requestBody)); } catch { promptInput = null; }
+ if (isRecord(promptInput) && Array.isArray(promptInput.files) && promptInput.files.length > 0) {
+ const converted = await convertOfficeAttachments(promptInput, input.workspace.path).catch(() => promptInput as Record<string, unknown>);
+ if (converted !== promptInput) {
+ body = JSON.stringify(converted);
+ headers.delete("content-length");
+ headers.set("content-type", "application/json");
+ }
+ }
+ }
// Collection, identical to the v1 mount: the session starts (or resumes) on
// its first dispatch, the prompt milestone is snapshotted, the request and
// response are traced and the turn is observed until it settles.