diff options
Diffstat (limited to '.rules')
| -rw-r--r-- | .rules/changelog/2026-03/29/01.md | 21 | ||||
| -rw-r--r-- | .rules/changelog/2026-03/29/02.md | 24 | ||||
| -rw-r--r-- | .rules/plans/image-attachment-part1.md | 267 | ||||
| -rw-r--r-- | .rules/plans/image-attachment-part2.md | 384 |
4 files changed, 696 insertions, 0 deletions
diff --git a/.rules/changelog/2026-03/29/01.md b/.rules/changelog/2026-03/29/01.md new file mode 100644 index 0000000..7a0c13f --- /dev/null +++ b/.rules/changelog/2026-03/29/01.md @@ -0,0 +1,21 @@ +# Changelog — 2026-03-29 — 01 + +## Image Attachment Backend (Part 1) + +### New Files + +- **`src/image-attachments.ts`** — Module-level storage for pending image attachments (`ImageAttachment` interface, `setCurrentAttachments`, `getCurrentAttachments`, `clearCurrentAttachments`, `hasCurrentAttachments`). +- **`src/context/tools/save-image.json`** — Tool context JSON for the `save_image` tool (id, label, description, friendlyName, requiresApproval, Ollama function definition with `file_path` parameter). + +### Modified Files + +- **`src/tools.ts`** + - Added imports for `save-image.json` and `image-attachments` module. + - Added `mimeToExtension()` helper mapping MIME types to file extensions. + - Added `executeSaveImage()` — saves attached images to vault, handles single/multi naming, creates parent folders, clears attachments after save. + - Added `save_image` entry to `TOOL_REGISTRY` with `approvalMessage`, `summarize`, `summarizeResult`, and `execute` callbacks. + +- **`src/ollama-client.ts`** + - Added import for `hasCurrentAttachments` from `image-attachments`. + - Added `"save_image"` case to `preValidateTool` switch. + - Added `preValidateSaveImage()` — validates `file_path` is provided and attachments exist before prompting user approval. diff --git a/.rules/changelog/2026-03/29/02.md b/.rules/changelog/2026-03/29/02.md new file mode 100644 index 0000000..5dc23b5 --- /dev/null +++ b/.rules/changelog/2026-03/29/02.md @@ -0,0 +1,24 @@ +# Image Attachment Feature — Part 2: Frontend UI + +## Files Modified + +### `src/chat-view.ts` +- Added imports for `setCurrentAttachments`, `clearCurrentAttachments`, and `ImageAttachment` from `./image-attachments` +- Added `PendingAttachment` interface (holds `File`, data URL, MIME type) +- Added class fields: `pendingAttachments`, `attachmentStrip`, `attachButton`, `fileInput` +- **`onOpen()`**: Added attachment preview strip (full-width, hidden when empty), attach button with `image-plus` icon (hidden when `save_image` tool is disabled), hidden `<input type="file">` with image MIME filter and `multiple` support +- **`handleSend()`**: Converts pending attachments to `ImageAttachment[]`, sets module-level attachments, prepends LLM context note instructing the AI to use `save_image`, shows original text in UI while sending augmented content in message history. Allows sending with images and no text. +- **`onClose()`**: Clears pending attachments and module-level attachments, nulls new DOM refs +- **Clear Chat handler**: Also clears pending and module-level attachments +- **Catch block**: Calls `clearCurrentAttachments()` on error/abort to prevent stale attachment leak +- **`setStreamingState()`**: Disables attach button during streaming +- **`updateAttachButtonVisibility()`**: New method that hides/shows the attach button based on whether `save_image` tool is enabled; called on open and when tools modal closes +- Added `handleFileSelection()`, `readFileAsDataUrl()`, `renderAttachmentStrip()` methods for file picking and thumbnail strip UI with per-thumbnail remove buttons + +### `styles.css` +- Updated `.ai-pulse-input-row` with `flex-wrap: wrap` and `align-items: flex-end` for strip-above-controls layout +- Added `.ai-pulse-attach-btn` (icon button with hover/disabled states) +- Added `.ai-pulse-attachment-strip` (horizontal scrollable thumbnail row, full width) +- Added `.ai-pulse-attachment-thumb` (48x48 thumbnail container with border) +- Added `.ai-pulse-attachment-thumb img` (cover-fit image) +- Added `.ai-pulse-attachment-remove` (circular × button, positioned top-right of thumb, red on hover) diff --git a/.rules/plans/image-attachment-part1.md b/.rules/plans/image-attachment-part1.md new file mode 100644 index 0000000..d7fa59f --- /dev/null +++ b/.rules/plans/image-attachment-part1.md @@ -0,0 +1,267 @@ +# Image Attachment — Part 1: Backend (Tool, Data Flow, Ollama Integration) + +## Overview + +This part creates the backend infrastructure for image attachments: the module-level attachment storage, the `save_image` tool (context JSON + execute function + registry entry), and the Ollama integration (pre-validation + context injection). + +**After this part is complete**, the `save_image` tool will be fully functional — it just won't have a UI to attach images yet. That comes in Part 2. + +--- + +## Step 1: Create `src/image-attachments.ts` + +Module-level storage for pending image attachments. The `ChatView` sets attachments before sending, and `executeSaveImage` reads them. + +```typescript +export interface ImageAttachment { + base64: string; + mimeType: string; + originalName: string; + arrayBuffer: ArrayBuffer; +} + +let currentAttachments: ImageAttachment[] = []; + +export function setCurrentAttachments(attachments: ImageAttachment[]): void { + currentAttachments = attachments; +} + +export function getCurrentAttachments(): ImageAttachment[] { + return currentAttachments; +} + +export function clearCurrentAttachments(): void { + currentAttachments = []; +} + +export function hasCurrentAttachments(): boolean { + return currentAttachments.length > 0; +} +``` + +--- + +## Step 2: Create `src/context/tools/save-image.json` + +Tool context JSON following the project convention (one JSON file per tool in `src/context/tools/`). + +```json +{ + "id": "save_image", + "label": "Save Image", + "description": "Save attached image(s) to the vault at a specified path.", + "friendlyName": "Save Image", + "requiresApproval": true, + "definition": { + "type": "function", + "function": { + "name": "save_image", + "description": "Save image(s) attached to the current chat message into the vault. The user has attached image(s) to their message — this tool writes them as files. You provide the vault-relative path WITHOUT the file extension (the correct extension is detected automatically from the image type). If multiple images are attached and you provide a single path, they will be saved as path_1.ext, path_2.ext, etc. If no images are attached, this tool returns an error. This action requires user approval.", + "parameters": { + "type": "object", + "required": ["file_path"], + "properties": { + "file_path": { + "type": "string", + "description": "The vault-relative path for the image WITHOUT the file extension. The extension is added automatically based on the image type (e.g., .jpg, .png). Example: 'attachments/cool-keyboard' will become 'attachments/cool-keyboard.jpg'. For multiple images with a single path, they are numbered: 'attachments/cool-keyboard_1.jpg', 'attachments/cool-keyboard_2.jpg', etc." + } + } + } + } + } +} +``` + +--- + +## Step 3: Add `executeSaveImage` and registry entry in `src/tools.ts` + +### Import + +```typescript +import saveImageCtx from "./context/tools/save-image.json"; +import { getCurrentAttachments, clearCurrentAttachments } from "./image-attachments"; +``` + +### MIME → Extension Map + +```typescript +function mimeToExtension(mimeType: string): string { + const map: Record<string, string> = { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/webp": ".webp", + "image/bmp": ".bmp", + "image/svg+xml": ".svg", + }; + return map[mimeType] ?? ".png"; +} +``` + +### Execute Function + +```typescript +async function executeSaveImage(app: App, args: Record<string, unknown>): Promise<string> { + const filePath = typeof args["file_path"] === "string" ? args["file_path"] : ""; + if (filePath === "") { + return "Error: file_path parameter is required."; + } + + const attachments = getCurrentAttachments(); + if (attachments.length === 0) { + return "Error: No images are attached to the current message."; + } + + const savedPaths: string[] = []; + const errors: string[] = []; + + for (let i = 0; i < attachments.length; i++) { + const attachment = attachments[i]; + if (attachment === undefined) continue; + + const ext = mimeToExtension(attachment.mimeType); + const fullPath = attachments.length === 1 + ? `${filePath}${ext}` + : `${filePath}_${i + 1}${ext}`; + + // Check if file already exists + const existing = app.vault.getAbstractFileByPath(fullPath); + if (existing !== null) { + errors.push(`"${fullPath}" already exists — skipped.`); + continue; + } + + // Ensure parent folder exists + const lastSlash = fullPath.lastIndexOf("/"); + if (lastSlash > 0) { + const folderPath = fullPath.substring(0, lastSlash); + const folder = app.vault.getFolderByPath(folderPath); + if (folder === null) { + await app.vault.createFolder(folderPath); + } + } + + try { + await app.vault.createBinary(fullPath, attachment.arrayBuffer); + savedPaths.push(fullPath); + } catch (err: unknown) { + const msg = err instanceof Error ? err.message : "Unknown error"; + errors.push(`"${fullPath}": ${msg}`); + } + } + + clearCurrentAttachments(); + + const parts: string[] = []; + if (savedPaths.length > 0) { + parts.push(`Saved ${savedPaths.length} image(s):\n${savedPaths.map(p => `- ${p}`).join("\n")}`); + } + if (errors.length > 0) { + parts.push(`Errors:\n${errors.map(e => `- ${e}`).join("\n")}`); + } + + return parts.join("\n\n"); +} +``` + +### Registry Entry + +Add to `TOOL_REGISTRY` array: + +```typescript +{ + ...asToolContext(saveImageCtx as Record<string, unknown>), + approvalMessage: (args) => { + const filePath = typeof args["file_path"] === "string" ? args["file_path"] : "unknown"; + const count = getCurrentAttachments().length; + return `Save ${count} image(s) to "${filePath}"?`; + }, + summarize: (args) => { + const filePath = typeof args["file_path"] === "string" ? args["file_path"] : ""; + const count = getCurrentAttachments().length; + return `${count} image(s) → "/${filePath}"`; + }, + summarizeResult: (result) => { + if (result.startsWith("Error")) return result; + if (result.includes("declined")) return "Declined by user"; + const match = result.match(/Saved (\d+) image/); + if (match !== null) return `${match[1]} image(s) saved`; + return "Images saved"; + }, + execute: executeSaveImage, +}, +``` + +--- + +## Step 4: Add pre-validation in `src/ollama-client.ts` + +### `preValidateSaveImage` Function + +Add to the `preValidateTool` switch: + +```typescript +case "save_image": + return preValidateSaveImage(app, args); +``` + +The validation function: + +```typescript +function preValidateSaveImage(_app: App, args: Record<string, unknown>): string | null { + const filePath = typeof args["file_path"] === "string" ? args["file_path"] : ""; + if (filePath === "") { + return "Error: file_path parameter is required."; + } + + // Import and check attachments + // Need to import: import { hasCurrentAttachments } from "./image-attachments"; + if (!hasCurrentAttachments()) { + return "Error: No images are attached to the current message. The user must attach images before you can save them."; + } + + return null; +} +``` + +### Import + +Add to `ollama-client.ts` imports: + +```typescript +import { hasCurrentAttachments } from "./image-attachments"; +``` + +### Context Injection + +In the `chatAgentLoop` function (or in the `sendChatMessageStreaming` function), before building the working messages, check if the **last user message** was sent with attachments. If so, prepend a context note to it. + +**Where to inject:** In `chat-view.ts`'s `handleSend()`, before pushing the user message to `this.messages`, modify the content if attachments are present: + +```typescript +let messageContent = text; +if (pendingAttachments.length > 0) { + const count = pendingAttachments.length; + messageContent = `[${count} image(s) are attached to this message. You MUST use the save_image tool to save them to the vault. Infer from the user's message how and where these images should be saved and embedded. Assume the user wants the images attached to whatever note they are asking you to create or edit.]\n\n${text}`; +} +``` + +The injected context is prepended to the user's message content, so: +- The AI always sees the attachment info alongside the user's request +- The display message (`appendMessage`) still shows only the original `text` +- The `messages[]` array (sent to LLM) contains the augmented `messageContent` + +**Note:** This injection happens in `chat-view.ts` (Part 2), but the logic is documented here for completeness. In Part 1, just ensure the `save_image` tool and pre-validation are ready. + +--- + +## Testing After Part 1 + +After completing Part 1, you can test manually by: + +1. Calling `setCurrentAttachments(...)` from the browser console with a test image +2. Sending a chat message asking the AI to save the image +3. Verifying the tool executes and writes the file to the vault + +The full UI integration comes in Part 2. diff --git a/.rules/plans/image-attachment-part2.md b/.rules/plans/image-attachment-part2.md new file mode 100644 index 0000000..c09fa18 --- /dev/null +++ b/.rules/plans/image-attachment-part2.md @@ -0,0 +1,384 @@ +# Image Attachment — Part 2: Frontend (UI, Chat View, CSS) + +## Overview + +This part adds the user-facing UI for image attachments: the attach button, file picker, thumbnail preview strip, and the integration in `handleSend()` that converts images and injects the context note for the AI. + +**Prerequisites:** Part 1 must be completed first (image-attachments module, save_image tool, pre-validation). + +--- + +## Step 5: Update `src/chat-view.ts` + +### New Imports + +```typescript +import { setCurrentAttachments, clearCurrentAttachments } from "./image-attachments"; +import type { ImageAttachment } from "./image-attachments"; +``` + +### New Class Fields + +```typescript +interface PendingAttachment { + file: File; + dataUrl: string; + mimeType: string; +} + +// In the ChatView class: +private pendingAttachments: PendingAttachment[] = []; +private attachmentStrip: HTMLDivElement | null = null; +private attachButton: HTMLButtonElement | null = null; +private fileInput: HTMLInputElement | null = null; +``` + +### UI Construction (in `onOpen()`) + +Update the input row section. Current structure: + +``` +[textarea] [send] +``` + +New structure: + +``` +[attachment-strip (above input row, hidden when empty)] +[attach-btn] [textarea] [send] +``` + +#### Attachment Strip (above input row) + +```typescript +// Before the inputRow creation: +this.attachmentStrip = messagesArea.createDiv({ cls: "ai-pulse-attachment-strip" }); +this.attachmentStrip.style.display = "none"; +``` + +#### Attach Button (left of textarea) + +```typescript +// Inside the inputRow, before the textarea: +this.attachButton = inputRow.createEl("button", { + cls: "ai-pulse-attach-btn", + attr: { "aria-label": "Attach image" }, +}); +setIcon(this.attachButton, "image-plus"); + +// Hidden file input +this.fileInput = inputRow.createEl("input", { + type: "file", + attr: { + accept: "image/jpeg,image/png,image/gif,image/webp,image/bmp,image/svg+xml", + multiple: "", + style: "display:none", + }, +}); + +this.attachButton.addEventListener("click", () => { + this.fileInput?.click(); +}); + +this.fileInput.addEventListener("change", () => { + if (this.fileInput === null || this.fileInput.files === null) return; + void this.handleFileSelection(this.fileInput.files); + this.fileInput.value = ""; // Reset so same file can be re-selected +}); +``` + +### File Selection Handler + +```typescript +private async handleFileSelection(files: FileList): Promise<void> { + for (let i = 0; i < files.length; i++) { + const file = files[i]; + if (file === undefined) continue; + if (!file.type.startsWith("image/")) continue; + + const dataUrl = await this.readFileAsDataUrl(file); + this.pendingAttachments.push({ + file, + dataUrl, + mimeType: file.type, + }); + } + this.renderAttachmentStrip(); +} + +private readFileAsDataUrl(file: File): Promise<string> { + return new Promise<string>((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + if (typeof reader.result === "string") { + resolve(reader.result); + } else { + reject(new Error("Failed to read file as data URL.")); + } + }; + reader.onerror = () => reject(new Error("File read error.")); + reader.readAsDataURL(file); + }); +} +``` + +### Thumbnail Strip Rendering + +```typescript +private renderAttachmentStrip(): void { + if (this.attachmentStrip === null) return; + this.attachmentStrip.empty(); + + if (this.pendingAttachments.length === 0) { + this.attachmentStrip.style.display = "none"; + return; + } + + this.attachmentStrip.style.display = "flex"; + + for (let i = 0; i < this.pendingAttachments.length; i++) { + const attachment = this.pendingAttachments[i]; + if (attachment === undefined) continue; + + const thumb = this.attachmentStrip.createDiv({ cls: "ai-pulse-attachment-thumb" }); + const img = thumb.createEl("img", { + attr: { src: attachment.dataUrl, alt: attachment.file.name }, + }); + void img; // suppress unused + + const removeBtn = thumb.createEl("button", { + cls: "ai-pulse-attachment-remove", + attr: { "aria-label": "Remove" }, + }); + setIcon(removeBtn, "x"); + + const index = i; + removeBtn.addEventListener("click", () => { + this.pendingAttachments.splice(index, 1); + this.renderAttachmentStrip(); + }); + } +} +``` + +### Update `handleSend()` + +In `handleSend()`, after getting the text and before pushing the user message: + +```typescript +// Convert pending attachments to ImageAttachment format for the tool +let messageContent = text; +if (this.pendingAttachments.length > 0) { + const imageAttachments: ImageAttachment[] = []; + for (const pa of this.pendingAttachments) { + const arrayBuffer = await pa.file.arrayBuffer(); + const bytes = new Uint8Array(arrayBuffer); + let binary = ""; + for (const b of bytes) binary += String.fromCharCode(b); + const base64 = btoa(binary); + + imageAttachments.push({ + base64, + mimeType: pa.mimeType, + originalName: pa.file.name, + arrayBuffer, + }); + } + + // Set the module-level attachments for the save_image tool to access + setCurrentAttachments(imageAttachments); + + // Prepend context note to the message for the LLM + const count = this.pendingAttachments.length; + messageContent = `[${count} image(s) are attached to this message. You MUST use the save_image tool to save them to the vault. Infer from the user's message how and where these images should be saved and embedded. Assume the user wants the images attached to whatever note they are asking you to create or edit.]\n\n${text}`; + + // Clear the UI attachments + this.pendingAttachments = []; + this.renderAttachmentStrip(); +} + +// Display the original text (without the context prefix) in the chat +this.appendMessage("user", text); + +// Track the augmented message in history for the LLM +this.messages.push({ role: "user", content: messageContent }); +``` + +**Important:** The existing code pushes `text` as the message content. Change it so: +- `appendMessage("user", text)` — shows original text in UI +- `this.messages.push({ role: "user", content: messageContent })` — sends augmented content to LLM + +### Clean Up on Close + +In `onClose()`: + +```typescript +this.pendingAttachments = []; +clearCurrentAttachments(); +this.attachmentStrip = null; +this.attachButton = null; +this.fileInput = null; +``` + +### Clean Up on Error/Abort + +In the `catch` block of `handleSend()`, if the send fails: + +```typescript +clearCurrentAttachments(); +``` + +This ensures stale attachments don't leak to the next message. + +### Streaming State + +When streaming starts, disable the attach button: + +```typescript +private setStreamingState(streaming: boolean): void { + // ...existing code... + if (this.attachButton !== null) { + this.attachButton.disabled = streaming; + } +} +``` + +--- + +## Step 6: CSS Changes (`styles.css`) + +### Attach Button + +```css +.ai-pulse-attach-btn { + flex-shrink: 0; + background: none; + border: none; + cursor: pointer; + padding: 4px; + border-radius: 4px; + color: var(--text-muted); + display: flex; + align-items: center; + justify-content: center; +} + +.ai-pulse-attach-btn:hover { + color: var(--text-normal); + background: var(--background-modifier-hover); +} + +.ai-pulse-attach-btn:disabled { + opacity: 0.4; + cursor: not-allowed; +} +``` + +### Attachment Preview Strip + +```css +.ai-pulse-attachment-strip { + display: flex; + gap: 6px; + padding: 6px 8px; + overflow-x: auto; + flex-wrap: nowrap; +} + +.ai-pulse-attachment-thumb { + position: relative; + width: 48px; + height: 48px; + border-radius: 4px; + overflow: visible; + flex-shrink: 0; + border: 1px solid var(--background-modifier-border); +} + +.ai-pulse-attachment-thumb img { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 4px; +} + +.ai-pulse-attachment-remove { + position: absolute; + top: -6px; + right: -6px; + width: 18px; + height: 18px; + border-radius: 50%; + background: var(--background-secondary); + border: 1px solid var(--background-modifier-border); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + padding: 0; + color: var(--text-muted); +} + +.ai-pulse-attachment-remove:hover { + background: var(--background-modifier-error); + color: var(--text-on-accent); +} + +.ai-pulse-attachment-remove svg { + width: 12px; + height: 12px; +} +``` + +### Input Row Update + +Ensure the input row uses flexbox with proper alignment: + +```css +.ai-pulse-input-row { + display: flex; + align-items: flex-end; + gap: 4px; + /* ...existing padding/margin styles... */ +} +``` + +--- + +## Step 7: Testing + +### Desktop +1. Open the chat panel +2. Click the attach button → file picker opens +3. Select one or more images → thumbnails appear in the strip +4. Click × on a thumbnail → it's removed +5. Type a message like "save this image to my notes/photos folder" +6. Send → AI calls save_image → approval prompt → image saved → AI embeds in note + +### Mobile +1. Same flow as desktop +2. File picker should open the camera roll / gallery +3. Verify the thumbnails render correctly on small screens +4. Verify the attach button is accessible and doesn't crowd the input + +### Edge Cases +- Send message with no text but images attached (should still work — the context note provides enough info) +- Abort mid-stream → attachments should be cleared +- Clear chat while attachments are pending → attachments should be cleared +- Multiple images with same name → numbered suffixes prevent collisions + +--- + +## Summary of All File Changes + +### Files Created (Part 1) +- `src/image-attachments.ts` +- `src/context/tools/save-image.json` + +### Files Modified (Part 1) +- `src/tools.ts` — new tool entry + execute function +- `src/ollama-client.ts` — pre-validation + +### Files Modified (Part 2) +- `src/chat-view.ts` — attach button, file picker, thumbnail strip, handleSend() changes +- `styles.css` — new CSS classes for attachment UI |
