feat(attachments): support local files and video attachments (#6321)
* feat(attachments): support local files and video attachments Share gateway inspection and send validation for borrowed local paths while preserving binary uploads, original-file ownership, and existing limits. Related to NAN-284. Native provider video input remains outside this change. * test: make cross-platform verification fixtures self-contained * test(webui): align typed fixtures with runtime contracts * fix(webui): preserve uploaded video playback during history sync * test(tui): preserve local attachment drafts across resizes * perf(attachments): preserve upload caches and release video previews * docs(webui): keep attachment guidance user-focused * chore: remove redundant dependency comment * test(providers): make stream idle renewal timing deterministic * fix(attachments): keep upload byte limits out of local references Validate common format/count rules separately from upload byte budgets. Keep local inspection and send-time checks metadata-only, and exclude local references from composer and pending-upload totals. Explain upload size rejections with actual size and maximum in all ten locales. Related to NAN-284. * fix(attachments): retain image references and draft order * fix(attachments): close local reference UX and authorization gaps * fix(attachments): preserve focus during asynchronous path confirmation
This commit is contained in:
1 parent
7dfeff9ddf
commit
254f94b068
65 files changed
+1816
-292
No files matched your search
+53
-12
@@ -1,3 +1,4 @@
|
||||
import { pastedFilePath, PastedPathRange } from "../../../packages/client-events/attachments"
|
||||
import {
|
||||
BoxRenderable,
|
||||
CliRenderEvents,
|
||||
@@ -221,6 +222,8 @@ export class NanobotTui {
|
||||
private apiRefreshPromise: Promise<GatewayApiConnection> | null = null
|
||||
private skillLoadId = 0
|
||||
private clipboardImagePending = false
|
||||
private pathInspection: PastedPathRange | null = null
|
||||
private get pathInspectionPending(): boolean { return this.pathInspection !== null }
|
||||
private clipboardPasteGeneration = 0
|
||||
private composerValue = ""
|
||||
private composerCursor = 0
|
||||
@@ -508,6 +511,10 @@ export class NanobotTui {
|
||||
private submit(): void {
|
||||
if (this.quitting || this.composer.isDestroyed) return
|
||||
const visibleContent = this.composer.plainText.trim()
|
||||
if (this.pathInspectionPending) {
|
||||
this.status.content = "Checking local attachment…"
|
||||
return
|
||||
}
|
||||
if (this.sessionLoading) {
|
||||
this.status.content = "Loading sessions…"
|
||||
return
|
||||
@@ -564,7 +571,7 @@ export class NanobotTui {
|
||||
}
|
||||
const command = this.commandMenu.resolve(visibleContent)
|
||||
if ((command || visibleContent.startsWith("!")) && this.draft.media(visibleContent).length) {
|
||||
this.status.content = "Remove the image before running a command."
|
||||
this.status.content = "Remove attachments before running a command."
|
||||
return
|
||||
}
|
||||
if (command?.source === "tui") {
|
||||
@@ -607,7 +614,7 @@ export class NanobotTui {
|
||||
this.attachmentSendPending = true
|
||||
const originalText = this.composer.plainText
|
||||
const chatId = this.client.activeChatId
|
||||
this.status.content = "Uploading attachments…"
|
||||
this.status.content = "Sending attachments…"
|
||||
void this.client.sendAttachments(prompt.content, prompt.options).then((turnId) => {
|
||||
if (this.client.activeChatId !== chatId || this.composer.plainText !== originalText) return
|
||||
this.sendPrompt(prompt, steering, turnId)
|
||||
@@ -1246,10 +1253,7 @@ export class NanobotTui {
|
||||
this.status.content = "Duplicate image placeholder. Rename or remove it before sending."
|
||||
return false
|
||||
}
|
||||
if (!this.hasPrompt(prompt)) return false
|
||||
if ((prompt.options.media?.length || 0) <= MAX_DRAFT_IMAGES) return true
|
||||
this.status.content = `Remove images until ${MAX_DRAFT_IMAGES} or fewer remain`
|
||||
return false
|
||||
return this.hasPrompt(prompt)
|
||||
}
|
||||
|
||||
private restoreQueuedPrompts(): void {
|
||||
@@ -1264,7 +1268,7 @@ export class NanobotTui {
|
||||
if (!this.activeTurn || !this.ready) return
|
||||
const visibleContent = this.composer.plainText.trim()
|
||||
if (this.draft.media(visibleContent).length) {
|
||||
this.status.content = "Images cannot be queued. Press Enter to send now."
|
||||
this.status.content = "Attachments cannot be queued. Press Enter to send now."
|
||||
return
|
||||
}
|
||||
if (this.commandMenu.resolve(visibleContent)?.source === "tui") {
|
||||
@@ -1874,6 +1878,11 @@ export class NanobotTui {
|
||||
value = edit.value
|
||||
cursor = edit.cursor
|
||||
}
|
||||
if (this.pathInspection && !this.pathInspection.update(value)) {
|
||||
this.pathInspection = null
|
||||
if (this.activeTurn) this.renderActiveStatus()
|
||||
else this.status.content = this.ready ? this.readyStatus() : this.connectionMessage
|
||||
}
|
||||
this.composerValue = value
|
||||
this.composerCursor = cursor
|
||||
this.draft.prune(value)
|
||||
@@ -1933,6 +1942,7 @@ export class NanobotTui {
|
||||
|
||||
private setComposer(content: string): void {
|
||||
this.clipboardPasteGeneration += 1
|
||||
this.pathInspection = null
|
||||
this.draft.clear()
|
||||
this.composer.setText(content)
|
||||
this.composer.cursorOffset = content.length
|
||||
@@ -1945,10 +1955,6 @@ export class NanobotTui {
|
||||
|
||||
private async pasteClipboardImage(): Promise<void> {
|
||||
if (this.clipboardImagePending) return
|
||||
if (this.draft.imageCount >= MAX_DRAFT_IMAGES) {
|
||||
this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images`
|
||||
return
|
||||
}
|
||||
const generation = this.clipboardPasteGeneration
|
||||
this.clipboardImagePending = true
|
||||
this.status.content = "Reading clipboard image…"
|
||||
@@ -1957,7 +1963,7 @@ export class NanobotTui {
|
||||
if (this.quitting || generation !== this.clipboardPasteGeneration) return
|
||||
const insertion = this.draft.image(image, this.composer.plainText)
|
||||
if (!insertion) {
|
||||
this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images`
|
||||
this.status.content = `A message can include up to ${MAX_DRAFT_IMAGES} images or files`
|
||||
return
|
||||
}
|
||||
this.composer.insertText(insertion.text)
|
||||
@@ -1981,6 +1987,41 @@ export class NanobotTui {
|
||||
private handlePaste(event: PasteEvent): void {
|
||||
event.preventDefault()
|
||||
const value = stripAnsiSequences(decodePasteBytes(event.bytes))
|
||||
const path = pastedFilePath(value)
|
||||
if (path && !this.pathInspectionPending) {
|
||||
this.composer.insertText(value)
|
||||
const pasted = this.composer.plainText
|
||||
const cursor = this.composerStringCursor()
|
||||
const generation = this.clipboardPasteGeneration
|
||||
const chatId = this.client.activeChatId
|
||||
const range = new PastedPathRange(pasted, cursor - value.length, cursor)
|
||||
this.pathInspection = range
|
||||
this.status.content = "Checking local attachment…"
|
||||
void this.client.inspectAttachment(path).then((file) => {
|
||||
if (this.quitting || this.composer.isDestroyed || generation !== this.clipboardPasteGeneration
|
||||
|| chatId !== this.client.activeChatId || this.pathInspection !== range) return
|
||||
if (!range.update(this.composer.plainText)) return
|
||||
const insertion = this.draft.localFile(file, this.composer.plainText)
|
||||
if (!insertion) throw new Error("Too many attachments; remove one and paste the path again")
|
||||
const edited = range.replace(insertion.text, this.composerStringCursor())!
|
||||
this.pathInspection = null
|
||||
this.composer.setText(edited.value)
|
||||
this.setComposerStringCursor(edited.value, edited.cursor)
|
||||
this.status.content = `Attached ${file.name}. Review before sending.`
|
||||
}).catch((error: unknown) => {
|
||||
if (generation !== this.clipboardPasteGeneration || this.quitting || this.pathInspection !== range) return
|
||||
this.pathInspection = null
|
||||
this.status.content = error instanceof Error ? error.message : "Attachment unavailable; path retained"
|
||||
}).finally(() => {
|
||||
if (this.pathInspection !== range) return
|
||||
this.pathInspection = null
|
||||
if (!this.quitting && !this.composer.isDestroyed) {
|
||||
if (this.activeTurn) this.renderActiveStatus()
|
||||
else this.status.content = this.ready ? this.readyStatus() : this.connectionMessage
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
const insertion = this.draft.paste(value)
|
||||
if (!insertion.text) return
|
||||
this.composer.insertText(insertion.text)
|
||||
|
||||
@@ -104,6 +104,119 @@ describe("NanobotTui composer", () => {
|
||||
expect(setup.captureCharFrame()).toContain("Ask nanobot anything")
|
||||
})
|
||||
|
||||
test("turns a confirmed pasted video path into a removable reference and retains failed sends", async () => {
|
||||
setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })
|
||||
const transport = client()
|
||||
transport.inspectAttachment = async (path) => {
|
||||
if (path.includes("missing")) throw new Error("file not found")
|
||||
return { path, name: "my clip.mp4", size: 6, kind: "video", mime: "video/mp4", url: "/api/media/sig/path" }
|
||||
}
|
||||
const sentOptions: MessageOptions[] = []
|
||||
transport.sendAttachments = async (_content, options) => {
|
||||
sentOptions.push(options)
|
||||
if (sentOptions.length === 1) throw new Error("source unavailable")
|
||||
return "accepted"
|
||||
}
|
||||
const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; status: { plainText: string } }
|
||||
await waitUntil(() => ui.ready)
|
||||
await setup.mockInput.pasteBracketedText('"/project/my clip.mp4"')
|
||||
await waitUntil(() => ui.composer.plainText.includes("[Video #1: my clip.mp4]"))
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => ui.status.plainText.includes("source unavailable"))
|
||||
expect(ui.composer.plainText).toContain("[Video #1: my clip.mp4]")
|
||||
expect(sentOptions[0]?.media).toEqual([{ path: "/project/my clip.mp4", name: "my clip.mp4" }])
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => ui.composer.plainText === "")
|
||||
await setup.mockInput.pasteBracketedText("./missing.mp4")
|
||||
await waitUntil(() => ui.status.plainText.includes("file not found"))
|
||||
expect(ui.composer.plainText).toBe("./missing.mp4")
|
||||
})
|
||||
|
||||
test.each([false, true])("preserves text %s while a native pasted path is checked", async (prepend) => {
|
||||
setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
|
||||
const transport = client()
|
||||
let complete!: (file: Awaited<ReturnType<typeof transport.inspectAttachment>>) => void
|
||||
transport.inspectAttachment = () => new Promise((resolve) => { complete = resolve })
|
||||
const sent: Array<{ content: string; options: MessageOptions }> = []
|
||||
transport.sendAttachments = async (content, options) => { sent.push({ content, options }); return "accepted" }
|
||||
const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; pathInspectionPending: boolean }
|
||||
await waitUntil(() => ui.ready)
|
||||
const path = "/project/image.png"
|
||||
await setup.mockInput.pasteBracketedText(path)
|
||||
if (prepend) ui.composer.cursorOffset = 0
|
||||
await setup.mockInput.typeText(prepend ? "请看 " : " describe it")
|
||||
complete({ path, name: "image.png", size: 6, kind: "image", mime: "image/png", url: "/api/media/sig/path" })
|
||||
await waitUntil(() => !ui.pathInspectionPending)
|
||||
expect(ui.composer.plainText).toContain("[Image #1: image.png]")
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => sent.length === 1)
|
||||
expect(sent[0]?.content).toBe(prepend ? "请看" : "describe it")
|
||||
expect(sent[0]?.options.media).toEqual([{ path, name: "image.png" }])
|
||||
})
|
||||
|
||||
test("cancels an edited native path and clears checking status without losing the text", async () => {
|
||||
setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
|
||||
const transport = client()
|
||||
let complete!: (file: Awaited<ReturnType<typeof transport.inspectAttachment>>) => void
|
||||
transport.inspectAttachment = () => new Promise((resolve) => { complete = resolve })
|
||||
const app = NanobotTui.mount(setup.renderer, options, transport, new MockTreeSitterClient({ autoResolveTimeout: 0 }))
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; pathInspectionPending: boolean; status: { plainText: string }; draft: { imageCount: number } }
|
||||
await waitUntil(() => ui.ready)
|
||||
await setup.mockInput.pasteBracketedText("/project/image.png")
|
||||
ui.composer.setText("/project/other.png")
|
||||
complete({ path: "/project/image.png", name: "image.png", size: 6, kind: "image", mime: "image/png", url: "/api/media/sig/path" })
|
||||
await waitUntil(() => !ui.pathInspectionPending)
|
||||
expect(ui.draft.imageCount).toBe(0)
|
||||
expect(ui.composer.plainText).toBe("/project/other.png")
|
||||
expect(ui.status.plainText).not.toContain("Checking local attachment")
|
||||
})
|
||||
|
||||
test("allows one referenced video plus four non-video attachments including a clipboard image", async () => {
|
||||
setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })
|
||||
const transport = client()
|
||||
transport.inspectAttachment = async (path) => ({
|
||||
path, name: path.split("/").at(-1)!, size: 6, url: "/api/media/sig/path",
|
||||
kind: path.endsWith("mp4") ? "video" : "file",
|
||||
mime: path.endsWith("mp4") ? "video/mp4" : "text/plain",
|
||||
})
|
||||
const sentOptions: MessageOptions[] = []
|
||||
transport.sendAttachments = async (_content, options) => { sentOptions.push(options); return "accepted" }
|
||||
const app = NanobotTui.mount(setup.renderer, options, transport,
|
||||
new MockTreeSitterClient({ autoResolveTimeout: 0 }), undefined,
|
||||
{ read: async () => ({ mimeType: "image/png", dataUrl: "data:image/png;base64,eA==" }), dispose: async () => {} })
|
||||
app.accept({ event: "attached", chat_id: "chat" })
|
||||
const ui = app as unknown as { ready: boolean; pathInspectionPending: boolean; composer: TextareaRenderable; draft: { imageCount: number }; status: { plainText: string } }
|
||||
await waitUntil(() => ui.ready)
|
||||
for (const [index, name] of ["clip.mp4", "one.txt", "two.txt", "three.txt"].entries()) {
|
||||
await setup.mockInput.pasteBracketedText(`/project/${name}`)
|
||||
await waitUntil(() => !ui.pathInspectionPending)
|
||||
expect(ui.draft.imageCount, `${name}: ${ui.composer.plainText}; ${ui.status.plainText}`).toBe(index + 1)
|
||||
}
|
||||
const beforeResize = ui.composer.plainText
|
||||
for (const width of [140, 40, 100]) {
|
||||
setup.resize(width, 30)
|
||||
await setup.flush()
|
||||
expect(ui.composer.plainText).toBe(beforeResize)
|
||||
expect(ui.draft.imageCount).toBe(4)
|
||||
}
|
||||
setup.mockInput.pressKey("v", { ctrl: true })
|
||||
await waitUntil(() => ui.draft.imageCount === 5)
|
||||
setup.mockInput.pressKey("v", { ctrl: true })
|
||||
await waitUntil(() => ui.status.plainText.includes("4 images or files"))
|
||||
expect(ui.draft.imageCount).toBe(5)
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => sentOptions.length === 1)
|
||||
expect(sentOptions[0]?.media).toHaveLength(5)
|
||||
expect(sentOptions[0]?.media?.filter((item) => item.path)).toHaveLength(4)
|
||||
expect(sentOptions[0]?.media?.at(-1)?.data_url).toBe("data:image/png;base64,eA==")
|
||||
await waitUntil(() => ui.composer.plainText === "")
|
||||
})
|
||||
|
||||
test("compacts large pastes in the composer without changing the sent text", async () => {
|
||||
const sent: string[] = []
|
||||
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
|
||||
@@ -248,7 +361,7 @@ describe("NanobotTui composer", () => {
|
||||
setup.mockInput.pressKey("v", { ctrl: true })
|
||||
await waitUntil(() => ui.composer.plainText === "这是什么? [Image #1] ")
|
||||
setup.mockInput.pressTab()
|
||||
expect(ui.status.plainText).toContain("Images cannot be queued")
|
||||
expect(ui.status.plainText).toContain("Attachments cannot be queued")
|
||||
expect(ui.composer.plainText).toBe("这是什么? [Image #1] ")
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => sent.length === 2)
|
||||
@@ -405,7 +518,7 @@ describe("NanobotTui composer", () => {
|
||||
setup.mockInput.pressKey("v", { ctrl: true })
|
||||
await waitUntil(() => ui.composer.plainText === "/model [Image #1] ")
|
||||
ui.composer.submit()
|
||||
await waitUntil(() => ui.status.plainText.includes("Remove the image before running a command."))
|
||||
await waitUntil(() => ui.status.plainText.includes("Remove attachments before running a command."))
|
||||
|
||||
expect(sent).toEqual([])
|
||||
expect(ui.composer.plainText).toBe("/model [Image #1] ")
|
||||
|
||||
@@ -69,6 +69,9 @@ export function client(
|
||||
async sendAttachments(content: string, messageOptions: MessageOptions) {
|
||||
return this.send(content, messageOptions)
|
||||
},
|
||||
async inspectAttachment(_path: string): Promise<import("../../../packages/client-events/attachments").LocalAttachment> {
|
||||
throw new Error("file not found")
|
||||
},
|
||||
attach(chatId: string) {
|
||||
attached.push(chatId)
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ThemeMode } from "@opentui/core"
|
||||
import type { LocalAttachment } from "../../../packages/client-events/attachments"
|
||||
|
||||
import type {
|
||||
GatewayConnection,
|
||||
@@ -33,6 +34,7 @@ export interface ChatClient {
|
||||
close(): void
|
||||
send(content: string, options?: MessageOptions): string
|
||||
sendAttachments(content: string, options: MessageOptions): Promise<string>
|
||||
inspectAttachment(path: string): Promise<LocalAttachment>
|
||||
attach(chatId: string): void
|
||||
newChat(scope?: WorkspaceScopePayload): void
|
||||
forkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): void
|
||||
|
||||
@@ -47,6 +47,7 @@ describe("TUI /usage", () => {
|
||||
activeChatId: "chat", connect() {}, close() {},
|
||||
send(content: string) { sent.push(content); return "turn" },
|
||||
async sendAttachments(content: string) { return this.send(content) },
|
||||
async inspectAttachment(): Promise<never> { throw new Error("file not found") },
|
||||
attach(chatId: string) { this.activeChatId = chatId },
|
||||
newChat() { this.activeChatId = "new-chat" },
|
||||
setWorkspaceScope() {},
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { pastedFilePath, uploadAttachments } from "../../../packages/client-events/attachments"
|
||||
|
||||
const originalFetch = globalThis.fetch
|
||||
afterEach(() => { globalThis.fetch = originalFetch })
|
||||
|
||||
test("recognizes whole paths across native platforms without consuming prose, code, URLs or fakepath", () => {
|
||||
for (const [text, path] of [
|
||||
['"C:\\project\\my clip.mp4"', "C:\\project\\my clip.mp4"],
|
||||
["'./clips/my clip.webm'", "./clips/my clip.webm"],
|
||||
["/tmp/my clip.mov", "/tmp/my clip.mov"], ["clips/clip.mp4", "clips/clip.mp4"],
|
||||
["clip.mp4", "clip.mp4"],
|
||||
['"C:\\project\\O\'Reilly.png"', "C:\\project\\O'Reilly.png"],
|
||||
["/tmp/O'Reilly.png", "/tmp/O'Reilly.png"],
|
||||
['"O\'Reilly notes.pdf"', "O'Reilly notes.pdf"],
|
||||
]) expect(pastedFilePath(text!)).toBe(path!)
|
||||
for (const text of ["please read ./file.txt", "const p = './file.txt'", "https://host/clip.mp4",
|
||||
"C:\\fakepath\\clip.mp4", "line\n./clip.mp4", "`./clip.mp4`"]) expect(pastedFilePath(text)).toBeNull()
|
||||
})
|
||||
|
||||
test("local paths send zero HTTP bodies; mixed batches upload only the required bytes", async () => {
|
||||
const requests: { url: string; body: Blob }[] = []
|
||||
globalThis.fetch = (async (url, init) => {
|
||||
requests.push({ url: String(url), body: init?.body as Blob })
|
||||
return Response.json({ reference: "upload-token" })
|
||||
}) as typeof fetch
|
||||
const local = { path: "/workspace/original.mp4", name: "original.mp4" }
|
||||
expect(await uploadAttachments([local], null, "ws://unused", () => true)).toEqual([local])
|
||||
expect(requests).toHaveLength(0)
|
||||
expect(await uploadAttachments([local, { data_url: "data:video/webm;base64,eA==", name: "upload.webm" }],
|
||||
{ path: "/api/attachments", token: "private-capability" }, "ws://localhost:1234", () => true))
|
||||
.toEqual([local, { reference: "upload-token", name: "upload.webm" }])
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(requests[0]?.url).toBe("http://localhost:1234/api/attachments")
|
||||
expect(await requests[0]?.body.text()).toBe("x")
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { uploadAttachments, uploadCapability, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments"
|
||||
import { uploadAttachments, uploadCapability, isLocalAttachment, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments"
|
||||
import { DeliveryReceipts } from "../../../packages/client-events/delivery"
|
||||
import { isRecoveryState } from "../../../packages/client-events/notifications"
|
||||
|
||||
@@ -249,6 +249,17 @@ export class NanobotClient {
|
||||
})
|
||||
}
|
||||
|
||||
inspectAttachment(path: string): Promise<import("../../../packages/client-events/attachments").LocalAttachment> {
|
||||
if (!this.chatId) return Promise.reject(new Error("chat is not ready"))
|
||||
return this.requestMutation<unknown>("attachment.inspect", {
|
||||
chat_id: this.chatId, path,
|
||||
...(this.workspaceScope ? { workspace_scope: this.workspaceScope } : {}),
|
||||
}).then((result) => {
|
||||
if (!isLocalAttachment(result)) throw new Error("Invalid attachment metadata")
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
private requestMutation<T>(
|
||||
action: string,
|
||||
payload: Record<string, unknown> = {},
|
||||
|
||||
@@ -71,10 +71,7 @@ export interface MediaAttachment {
|
||||
name?: string
|
||||
}
|
||||
|
||||
export interface OutboundMedia {
|
||||
data_url: string
|
||||
name?: string
|
||||
}
|
||||
export type OutboundMedia = import("../../../packages/client-events/attachments").DraftAttachment
|
||||
|
||||
export interface WorkspaceScopePayload {
|
||||
project_path: string
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { OutboundMedia } from "../client"
|
||||
import type { LocalAttachment } from "../../../packages/client-events/attachments"
|
||||
|
||||
const LARGE_PASTE_CHARS = 1_000
|
||||
const LARGE_PASTE_LINES = 10
|
||||
@@ -31,7 +32,7 @@ interface DraftImage {
|
||||
/** Keeps large pasted text and image payloads out of the editable composer surface. */
|
||||
export class ComposerDraft {
|
||||
private readonly pastes = new Map<string, string>()
|
||||
private readonly images = new Map<string, OutboundMedia>()
|
||||
private readonly images = new Map<string, OutboundMedia & { kind: LocalAttachment["kind"] }>()
|
||||
|
||||
get imageCount(): number {
|
||||
return this.images.size
|
||||
@@ -67,16 +68,30 @@ export class ComposerDraft {
|
||||
}
|
||||
|
||||
image(image: DraftImage, visible = ""): PasteInsertion | null {
|
||||
if (this.images.size >= MAX_DRAFT_IMAGES) return null
|
||||
if ([...this.images.values()].filter((item) => item.kind !== "video").length >= MAX_DRAFT_IMAGES) return null
|
||||
const index = this.nextImageIndex(visible)
|
||||
const label = `[Image #${index}]`
|
||||
this.images.set(label, {
|
||||
kind: "image",
|
||||
data_url: image.dataUrl,
|
||||
name: `clipboard-image-${index}.${IMAGE_EXTENSIONS[image.mimeType]}`,
|
||||
})
|
||||
return { text: `${label} `, compacted: true, description: label.slice(1, -1) }
|
||||
}
|
||||
|
||||
localFile(file: LocalAttachment, visible = ""): PasteInsertion | null {
|
||||
const current = [...this.images.values()]
|
||||
if (file.kind === "video"
|
||||
? current.some((item) => item.kind === "video")
|
||||
: current.filter((item) => item.kind !== "video").length >= MAX_DRAFT_IMAGES) return null
|
||||
const prefix = file.kind === "video" ? "Video" : file.kind === "image" ? "Image" : "File"
|
||||
let index = 1
|
||||
let label = `[${prefix} #${index}: ${file.name}]`
|
||||
while (this.imageLabelInUse(label, visible)) label = `[${prefix} #${++index}: ${file.name}]`
|
||||
this.images.set(label, { kind: file.kind, path: file.path, name: file.name })
|
||||
return { text: `${label} `, compacted: true, description: label.slice(1, -1) }
|
||||
}
|
||||
|
||||
private expandPastes(visible: string): string {
|
||||
let expanded = visible
|
||||
for (const [label, content] of this.pastes) expanded = expanded.split(label).join(content)
|
||||
@@ -180,7 +195,7 @@ export class ComposerDraft {
|
||||
return [...this.images]
|
||||
.filter(([label]) => visible.includes(label))
|
||||
.sort(([left], [right]) => visible.indexOf(left) - visible.indexOf(right))
|
||||
.map(([, media]) => media)
|
||||
.map(([, { kind: _kind, ...media }]) => media)
|
||||
}
|
||||
|
||||
prune(visible: string): void {
|
||||
|
||||
Reference in new issue
Block a user