Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
send a photo from the Shell tab to the agent TUI running in that session
[._.]/ Adam Eivya93f2ed9b44e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a196d87a46..e2a6a21e0f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Added- **The SongBook's sample song now ships a drum part.** "House of the Rising Sun" has always seeded with guitar, piano, and ukulele arrangements, but a drummer opening it had nothing to read — only the invented "Example Rock Beat" that exists to demonstrate the grid format. A fourth arrangement now ships alongside the other three: 32 bars of 6/8 (one grid cell per eighth, four times through the 8-bar progression), with the drums sitting out the intro on a hi-hat foot pulse, entering on a pickup fill, moving from hats to the ride for the organ break, and ending on a flam into the crash. It plays back against the other three seeds at the same tempo, and the written 228 counts *eighths* — so the practice-tempo buttons take it down to a workable speed. Existing installs receive it on upgrade without ever overwriting a copy you've edited or deleted.+- **The Shell tab can now hand a photo to the agent running in it.** A new **Photo** button in the terminal toolbar (and in the fullscreen control bar) opens a small composer: choose a photo, snap one from your phone, drag one in, or paste a screenshot straight from the clipboard, type a message, and send. PortOS saves the image and types your message plus the saved image's path into the live session as a single paste, so a running `claude` or `codex` can read the picture and answer about it — the same way you'd hand it a file if you were sitting at the terminal. Enter sends, Shift+Enter adds a line; a failed send keeps your message and your picked photo so you can retry without retyping. Photos are stored under a unique name, so sending two shots from a phone (where every photo is `IMG_0001.jpg`) can't have the second overwrite the first before the agent has read it.- **Malware scans now leave a durable, reviewable report trail.** Git-link scans save an owned markdown artifact, surface it from the completed agent summary and Review Hub, and mark repositories with an explicit `DANGEROUS` verdict using a skull danger treatment on the Git links card.- **Slashdo-free TUI agent PRs now complete their lifecycle.** Codex, Antigravity, OpenCode, and lean Claude agents hand committed work back to PortOS so it can generate a non-empty PR description, run configured reviewers, and merge after the selected gates pass instead of leaving an ownerless PR open.- **Music Video projects now save their scene-video renderer and model.** Directors can choose local or Grok generation per project, pick an image-to-video-capable local model, see cut-pacing warnings, selectively continue clips on native LTX runtimes, generate all missing media from the board, and play or download the audio-backed final render in place.diff --git a/client/src/components/shell/ShellImageDrop.jsx b/client/src/components/shell/ShellImageDrop.jsxnew file mode 100644index 0000000000..bb2ab7c712--- /dev/null+++ b/client/src/components/shell/ShellImageDrop.jsx@@ -0,0 +1,229 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { ImageUp, Send, X } from 'lucide-react';+import FilePickerButton from '../ui/FilePickerButton';+import FormField from '../ui/FormField';+import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';+import useEscapeKey from '../../hooks/useEscapeKey';+import { IMAGE_ACCEPT, validateImageFile } from '../../utils/fileUpload';+import { formatBytes } from '../../utils/formatters';+import toast from '../ui/Toast';++const PANEL_WIDTH = 352;++/**+ * "Photo" button + composer popover for the Shell page: pick (or snap, or paste,+ * or drag) an image, type a message, and send both to whatever is running in the+ * active session — the point being a live `claude`/`codex` TUI, which reads the+ * image off disk from the path the server pastes in.+ *+ * The picker is `IMAGE_ACCEPT` (png/jpeg/webp) rather than `image/*` on purpose:+ * naming `image/jpeg` is what makes iOS transcode a HEIC camera roll photo to+ * JPEG on the way out, and the server only accepts formats it can magic-byte+ * verify. No `capture` attribute — that would force camera-only and lock the user+ * out of their photo library; the iOS sheet already offers "Take Photo".+ *+ * The panel is PORTALED and fixed-positioned via `usePopoverPosition`, which+ * measures the trigger and clamps/flips into the viewport. Both hosts need that:+ * the fullscreen control bar is `overflow-x-auto` (an `auto` overflow on one axis+ * makes the other clip too, so an in-flow absolute panel would be cut off) and it+ * scrolls horizontally, so a hardcoded offset would detach from the button.+ *+ * @param {Object} props+ * @param {(file: File, message: string) => Promise<boolean>} props.onSend - resolves+ * true once the server confirms the paste; a false keeps the composer open with+ * the user's message intact so they can retry without retyping.+ * @param {'below'|'above'} [props.placement] - preferred side; flips if there's no room+ */+export default function ShellImageDrop({ onSend, placement = 'below' }) {+ const [open, setOpen] = useState(false);+ // One piece of state, not a `file`/`preview` pair kept in lockstep — divergence+ // becomes unrepresentable and the render branch needs no optional chaining.+ const [picked, setPicked] = useState(null);+ const [message, setMessage] = useState('');+ const [sending, setSending] = useState(false);+ const containerRef = useRef(null);+ const { triggerRef, popoverRef, style } = usePopoverPosition({+ open,+ width: PANEL_WIDTH,+ position: placement === 'above' ? 'above' : 'below',+ // The panel's height changes when the picker swaps for the thumbnail, so+ // re-measure on that (it decides whether the preferred side still fits).+ contentDeps: [!!picked],+ });++ // Object URLs are revoked on replacement and on unmount — a long Shell session+ // where the user sends a dozen photos would otherwise pin every one in memory.+ useEffect(() => {+ if (!picked) return undefined;+ return () => URL.revokeObjectURL(picked.url);+ }, [picked]);++ const selectFile = useCallback((file) => {+ if (!file) return;+ const problem = validateImageFile(file);+ if (problem) {+ toast.error(problem);+ return;+ }+ setPicked({ file, url: URL.createObjectURL(file) });+ }, []);++ const close = useCallback(() => {+ setOpen(false);+ setPicked(null);+ setMessage('');+ }, []);++ const handleDrop = useCallback((e) => {+ e.preventDefault();+ selectFile(e.dataTransfer?.files?.[0]);+ }, [selectFile]);++ // Desktop screenshot → Cmd+Shift+Ctrl+4 → paste straight into the composer.+ const handlePaste = useCallback((e) => {+ const pasted = Array.from(e.clipboardData?.files || [])+ .find(f => f.type.startsWith('image/'));+ if (!pasted) return;+ e.preventDefault();+ selectFile(pasted);+ }, [selectFile]);++ const send = useCallback(async () => {+ if (!picked || sending) return;+ setSending(true);+ const ok = await onSend(picked.file, message.trim());+ setSending(false);+ // Only tear the composer down on success — on failure the user keeps their+ // message and picked file and can retry.+ if (ok) close();+ }, [picked, message, onSend, sending, close]);++ useEscapeKey(open, close);++ // Click-outside is hand-rolled rather than `useClickOutside` (and NOT an+ // oversight): that hook decides "outside" from a SINGLE ref, and this panel is+ // portaled to <body>, so it isn't a descendant of the trigger container — the+ // hook would treat every click on the textarea as outside and close the+ // composer mid-typing. Two refs have to be consulted. Same shape as the other+ // portaled popover, ThemeSwitcher.jsx.+ useEffect(() => {+ if (!open) return undefined;+ const onMouseDown = (e) => {+ const inTrigger = containerRef.current?.contains(e.target);+ const inPanel = popoverRef.current?.contains(e.target);+ if (!inTrigger && !inPanel) close();+ };+ document.addEventListener('mousedown', onMouseDown);+ return () => document.removeEventListener('mousedown', onMouseDown);+ }, [open, close, popoverRef]);++ return (+ <div className="relative shrink-0" ref={containerRef}>+ <button+ ref={triggerRef}+ onClick={() => (open ? close() : setOpen(true))}+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-mono transition-colors border min-h-[40px] shrink-0 ${+ open+ ? 'bg-port-accent/25 text-port-accent border-port-accent/50'+ : 'bg-port-accent/15 hover:bg-port-accent/25 text-port-accent hover:text-port-accent/80 border-port-accent/30'+ }`}+ title="Send a photo to this session"+ aria-label="Send a photo to this session"+ aria-expanded={open}+ >+ <ImageUp size={14} />+ <span className="hidden sm:inline">Photo</span>+ </button>++ {open && createPortal(+ <div+ ref={popoverRef}+ onPaste={handlePaste}+ onDrop={handleDrop}+ onDragOver={(e) => e.preventDefault()}+ className="fixed max-w-[calc(100vw-1rem)] z-[100] p-3 bg-port-card border border-port-border rounded-lg shadow-xl space-y-2"+ style={{+ left: style?.left ?? `${VIEWPORT_PADDING}px`,+ top: style?.top ?? `${VIEWPORT_PADDING}px`,+ width: style?.width ?? `${PANEL_WIDTH}px`,+ // Hidden until measured so the panel never flashes at the corner.+ visibility: style ? 'visible' : 'hidden',+ }}+ >+ {picked ? (+ <div className="flex items-start gap-2">+ <img+ src={picked.url}+ alt={picked.file.name}+ className="w-16 h-16 object-cover rounded border border-port-border"+ />+ <div className="flex-1 min-w-0">+ <div className="text-xs text-gray-300 truncate" title={picked.file.name}>{picked.file.name}</div>+ <div className="text-xs text-gray-500 font-mono">{formatBytes(picked.file.size)}</div>+ </div>+ <button+ onClick={() => setPicked(null)}+ className="p-1 text-gray-400 hover:text-white transition-colors"+ title="Remove image"+ aria-label="Remove image"+ >+ <X size={14} />+ </button>+ </div>+ ) : (+ <FilePickerButton+ accept={IMAGE_ACCEPT}+ onChange={(e) => selectFile(e.target.files?.[0])}+ className="flex flex-col items-center justify-center gap-1 w-full py-4 border border-dashed border-port-border hover:border-port-accent/50 rounded text-xs text-gray-400 hover:text-gray-200 transition-colors"+ ariaLabel="Choose a photo to send to this session"+ >+ <ImageUp size={18} />+ <span>Choose, drop, or paste a photo</span>+ </FilePickerButton>+ )}++ <FormField label="Message" labelClassName="block text-xs text-gray-400 mb-1">+ <textarea+ value={message}+ onChange={(e) => setMessage(e.target.value)}+ onKeyDown={(e) => {+ // Enter sends, Shift+Enter adds a newline — the same contract as+ // every other agent prompt box in PortOS.+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ send();+ }+ }}+ rows={2}+ placeholder="What should the agent do with this photo?"+ className="w-full px-2 py-1.5 bg-port-bg text-white text-xs rounded border border-port-border focus:outline-none focus:border-port-accent placeholder-gray-500 resize-y"+ />+ </FormField>++ <div className="flex items-center gap-2">+ <button+ onClick={send}+ disabled={!picked || sending}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded text-xs transition-colors min-h-[40px]"+ >+ <Send size={14} />+ {sending ? 'Sending…' : 'Send'}+ </button>+ <button+ onClick={close}+ className="px-3 py-1.5 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded text-xs transition-colors border border-port-border min-h-[40px]"+ >+ Cancel+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Pastes the message plus the saved image path into the session, so a running+ agent can read it.+ </p>+ </div>,+ document.body+ )}+ </div>+ );+}diff --git a/client/src/components/shell/ShellImageDrop.test.jsx b/client/src/components/shell/ShellImageDrop.test.jsxnew file mode 100644index 0000000000..c2e6c7cd3e--- /dev/null+++ b/client/src/components/shell/ShellImageDrop.test.jsx@@ -0,0 +1,134 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import ShellImageDrop from './ShellImageDrop';++const toastMock = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('../ui/Toast', () => ({ default: toastMock }));++const imageFile = (name = 'photo.jpg', { size = 1024, type = 'image/jpeg' } = {}) => {+ const f = new File(['x'], name, { type });+ Object.defineProperty(f, 'size', { value: size });+ return f;+};++// The picker input is the only labelled file control in the panel.+const pickFile = (file) => {+ const input = screen.getByLabelText('Choose a photo to send to this session');+ Object.defineProperty(input, 'files', { configurable: true, get: () => [file] });+ fireEvent.change(input);+};++const openComposer = () => fireEvent.click(screen.getByRole('button', { name: /send a photo/i }));++beforeEach(() => {+ vi.clearAllMocks();+ global.URL.createObjectURL = vi.fn(() => 'blob:preview');+ global.URL.revokeObjectURL = vi.fn();+});++describe('ShellImageDrop', () => {+ it('keeps the composer closed until the Photo button is clicked', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ expect(screen.queryByLabelText(/choose a photo/i)).toBeNull();+ openComposer();+ expect(screen.getByLabelText(/choose a photo/i)).toBeTruthy();+ });++ it('sends the picked file with the typed message', async () => {+ const onSend = vi.fn().mockResolvedValue(true);+ render(<ShellImageDrop onSend={onSend} />);+ openComposer();++ const file = imageFile();+ pickFile(file);+ fireEvent.change(screen.getByLabelText('Message'), { target: { value: ' what is this? ' } });+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ // The message is trimmed before it reaches the PTY.+ await waitFor(() => expect(onSend).toHaveBeenCalledWith(file, 'what is this?'));+ });++ it('sends with no message when the box is left empty', async () => {+ const onSend = vi.fn().mockResolvedValue(true);+ render(<ShellImageDrop onSend={onSend} />);+ openComposer();+ const file = imageFile();+ pickFile(file);+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => expect(onSend).toHaveBeenCalledWith(file, ''));+ });++ it('closes and clears on a successful send', async () => {+ render(<ShellImageDrop onSend={vi.fn().mockResolvedValue(true)} />);+ openComposer();+ pickFile(imageFile());+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => expect(screen.queryByLabelText('Message')).toBeNull());+ });++ // A failed send must not throw away what the user typed — otherwise a transient+ // upload failure costs them the message and the file pick.+ it('stays open with the message intact when the send fails', async () => {+ render(<ShellImageDrop onSend={vi.fn().mockResolvedValue(false)} />);+ openComposer();+ pickFile(imageFile());+ fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'retry me' } });+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled());+ expect(screen.getByLabelText('Message').value).toBe('retry me');+ expect(screen.getByAltText('photo.jpg')).toBeTruthy();+ });++ it('cannot send without an image', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ openComposer();+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();+ });++ it('rejects a file over the screenshot size cap without selecting it', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ openComposer();+ pickFile(imageFile('huge.jpg', { size: 20 * 1024 * 1024 }));+ expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining('exceeds'));+ expect(screen.queryByAltText('huge.jpg')).toBeNull();+ });++ it('rejects a non-image file', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ openComposer();+ pickFile(imageFile('notes.txt', { type: 'text/plain' }));+ expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining('not an image'));+ });++ it('accepts a pasted image', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ openComposer();+ const file = imageFile('pasted.png', { type: 'image/png' });+ fireEvent.paste(screen.getByLabelText('Message'), { clipboardData: { files: [file] } });+ expect(screen.getByAltText('pasted.png')).toBeTruthy();+ });++ it('Enter sends and Shift+Enter does not', async () => {+ const onSend = vi.fn().mockResolvedValue(true);+ render(<ShellImageDrop onSend={onSend} />);+ openComposer();+ pickFile(imageFile());+ const box = screen.getByLabelText('Message');++ fireEvent.keyDown(box, { key: 'Enter', shiftKey: true });+ expect(onSend).not.toHaveBeenCalled();++ fireEvent.keyDown(box, { key: 'Enter' });+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ });++ it('removes a picked image without closing the composer', () => {+ render(<ShellImageDrop onSend={vi.fn()} />);+ openComposer();+ pickFile(imageFile());+ fireEvent.click(screen.getByRole('button', { name: 'Remove image' }));+ expect(screen.queryByAltText('photo.jpg')).toBeNull();+ expect(screen.getByLabelText(/choose a photo/i)).toBeTruthy();+ });+});diff --git a/client/src/components/shell/TerminalHotKeys.jsx b/client/src/components/shell/TerminalHotKeys.jsxindex 2dc95cb4c9..e84eee11a0 100644--- a/client/src/components/shell/TerminalHotKeys.jsx+++ b/client/src/components/shell/TerminalHotKeys.jsx@@ -1,4 +1,5 @@import { OctagonX, ChevronsLeft, ClipboardPaste, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft } from 'lucide-react';+import ShellImageDrop from './ShellImageDrop';// Hot buttons for arrow / Enter entry — handy on touch devices and for driving TUI// apps or scrolling shell history without a hardware keyboard. Arrow keys carry the@@ -15,10 +16,13 @@ export const NAV_KEYS = [];// Touch-friendly TUI-driving controls shared by the inline quick-commands toolbar-// and the fullscreen control bar: Ctrl+B/C, Paste (+ fallback paste input), and the-// arrow / Enter hot buttons. The Ctrl+B/C / Paste text labels collapse below `sm` so-// the cluster stays narrow on a phone; the icons always show.-export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, sendNavKey, showPasteInput, setShowPasteInput, pasteInputRef, handlePasteInputEvent }) {+// and the fullscreen control bar: Ctrl+B/C, Paste (+ fallback paste input), Photo,+// and the arrow / Enter hot buttons. The Ctrl+B/C / Paste text labels collapse+// below `sm` so the cluster stays narrow on a phone; the icons always show.+//+// `popoverPlacement` is which way the Photo composer opens — 'above' for the+// fullscreen bar, which is pinned to the bottom of the viewport.+export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, sendNavKey, showPasteInput, setShowPasteInput, pasteInputRef, handlePasteInputEvent, sendImage, popoverPlacement = 'below' }) {return (<><button@@ -58,6 +62,7 @@ export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, senonBlur={() => setShowPasteInput(false)}/>)}+ <ShellImageDrop onSend={sendImage} placement={popoverPlacement} /><div className="w-px h-6 bg-port-border shrink-0" />{/* Arrow / Enter hot buttons — touch-friendly TUI nav + shell history */}{NAV_KEYS.map((key) => (diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ef7f96c5c0..8021ee9442 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -75,7 +75,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |-| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendCommand, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |+| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. || `useUpdateChecker` | Detect stale client bundle; show reload toast. | Wire once at app root. || `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. || `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.jsindex da2cd2bd55..0ddd0b398c 100644--- a/client/src/hooks/useShellSession.js+++ b/client/src/hooks/useShellSession.js@@ -7,6 +7,9 @@ import '@xterm/xterm/css/xterm.css';import { useSocket } from './useSocket';import { useThemeContext } from '../components/ThemeContext';import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';+import { readFileAsBase64 } from '../utils/fileUpload';+import * as api from '../services/api';+import toast from '../components/ui/Toast';// Must match MAX_TOTAL_SESSIONS in server/services/shell.jsexport const MAX_SESSIONS = 20;@@ -152,6 +155,44 @@ export function useShellSession({ isFullscreen } = {}) {if (focus) termInstanceRef.current?.focus();}, [socket]);+ // Send a photo (plus an optional message) to whatever is running in the active+ // session — the point being a live `claude`/`codex` TUI, which reads images off+ // disk. This one goes over HTTP, not the `shell:*` socket protocol: socket.io's+ // 1MB frame limit can't carry a photo, and it's a one-shot request that needs a+ // result. The server saves the bytes and bracket-pastes `<message>\n<path>` into+ // the PTY; the path never comes back, so nothing here can leak the install layout.+ //+ // Resolves true only on success, so the caller can keep its composer open (with+ // the user's message intact) to retry. Errors are toasted here — the guard+ // refusals have no other error surface, so this owns all of them and the API call+ // is `silent`.+ const sendImage = useCallback(async (file, message = '') => {+ if (!sessionIdRef.current) {+ toast.error('No active shell session');+ return false;+ }+ // Same guard as emitShellInput: a mid-switch send would land in the session+ // the user is leaving.+ if (pendingAttachRef.current.target) {+ toast.error('Session is still attaching — try again in a moment');+ return false;+ }+ const sessionId = sessionIdRef.current;+ const data = await readFileAsBase64(file).catch(() => null);+ if (!data) {+ toast.error(`Failed to read ${file.name}`);+ return false;+ }+ const sent = await api.sendShellImage(sessionId, { data, filename: file.name, message }, { silent: true })+ .catch((err) => {+ toast.error(`Failed to send image: ${err.message}`);+ return null;+ });+ if (!sent) return false;+ toast.success('Image sent to session');+ return true;+ }, []);+const sendCommand = useCallback((cmd) => emitShellInput(cmd + '\n'), [emitShellInput]);const sendCtrlB = useCallback(() => emitShellInput('\x02'), [emitShellInput]);const sendCtrlC = useCallback(() => emitShellInput('\x03'), [emitShellInput]);@@ -790,6 +831,7 @@ export function useShellSession({ isFullscreen } = {}) {liveRunCount,isLiveRun,emitShellInput,+ sendImage,sendCommand,sendCtrlB,sendCtrlC,diff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsxindex bda79ab923..bdb4add091 100644--- a/client/src/hooks/useShellSession.test.jsx+++ b/client/src/hooks/useShellSession.test.jsx@@ -24,6 +24,14 @@ vi.mock('../services/socket', () => ({ default: socketMock, getSocket: () => socvi.mock('../components/ThemeContext', () => ({useThemeContext: () => ({ themeId: 'test', theme: { mode: 'night' } }),}));+const { readFileAsBase64, sendShellImage, toastMock } = vi.hoisted(() => ({+ readFileAsBase64: vi.fn(),+ sendShellImage: vi.fn(),+ toastMock: { error: vi.fn(), success: vi.fn() },+}));+vi.mock('../utils/fileUpload', () => ({ readFileAsBase64 }));+vi.mock('../services/api', () => ({ sendShellImage }));+vi.mock('../components/ui/Toast', () => ({ default: toastMock }));import { useShellSession, MAX_SESSIONS } from './useShellSession.js';@@ -101,4 +109,69 @@ describe('useShellSession', () => {it('exports the shell session cap', () => {expect(MAX_SESSIONS).toBe(20);});++ // sendImage goes over HTTP, not the shell:* socket protocol — socket.io's 1MB+ // frame limit can't carry a photo, and it needs a result.+ describe('sendImage', () => {+ const photo = new File(['x'], 'photo.jpg', { type: 'image/jpeg' });++ const activeHook = () => {+ const rendered = renderHook(() => useShellSession({}), { wrapper });+ fire('shell:sessions', []);+ fire('shell:started', { sessionId: 'abc' });+ return rendered;+ };++ beforeEach(() => {+ readFileAsBase64.mockReset().mockResolvedValue('Zm9v');+ sendShellImage.mockReset().mockResolvedValue({ sessionId: 'abc', filename: 'shell-aa11bb22-photo.jpg' });+ toastMock.error.mockReset();+ toastMock.success.mockReset();+ });++ it('posts the bytes to the active session and resolves true', async () => {+ const { result } = activeHook();+ await expect(result.current.sendImage(photo, 'what is this?')).resolves.toBe(true);++ // `silent` because this hook owns the error toast — otherwise the user sees two.+ expect(sendShellImage).toHaveBeenCalledWith(+ 'abc',+ { data: 'Zm9v', filename: 'photo.jpg', message: 'what is this?' },+ { silent: true },+ );+ expect(toastMock.success).toHaveBeenCalled();+ });++ it('resolves false and toasts when the server rejects the send', async () => {+ sendShellImage.mockRejectedValue(new Error('Session not found'));+ const { result } = activeHook();+ await expect(result.current.sendImage(photo, 'hi')).resolves.toBe(false);+ expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining('Session not found'));+ expect(toastMock.success).not.toHaveBeenCalled();+ });++ it('resolves false without posting when the file cannot be read', async () => {+ readFileAsBase64.mockRejectedValue(new Error('boom'));+ const { result } = activeHook();+ await expect(result.current.sendImage(photo, 'hi')).resolves.toBe(false);+ expect(sendShellImage).not.toHaveBeenCalled();+ });++ it('refuses to send when there is no active session', async () => {+ const { result } = renderHook(() => useShellSession({}), { wrapper });+ await expect(result.current.sendImage(photo, 'hi')).resolves.toBe(false);+ expect(readFileAsBase64).not.toHaveBeenCalled();+ });++ // Mid-switch the terminal has been cleared and the pending target is another+ // session — a send here would land in the session the user is leaving.+ it('refuses to send while an attach is in flight', async () => {+ const { result } = renderHook(() => useShellSession({}), { wrapper });+ fire('shell:sessions', [session('s1')]);+ fire('shell:attached', { sessionId: 's1', bufferedOutput: '' });+ act(() => result.current.switchToSession('s2'));+ await expect(result.current.sendImage(photo, 'hi')).resolves.toBe(false);+ expect(readFileAsBase64).not.toHaveBeenCalled();+ });+ });});diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex c1f8da8a7d..dac8d44d93 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -40,6 +40,7 @@ export default function Shell() {liveRunCount,isLiveRun,emitShellInput,+ sendImage,sendCommand,sendCtrlB,sendCtrlC,@@ -192,6 +193,7 @@ export default function Shell() {setShowPasteInput={setShowPasteInput}pasteInputRef={pasteInputRef}handlePasteInputEvent={handlePasteInputEvent}+ sendImage={sendImage}/><div className="w-px h-6 bg-port-border" />{QUICK_COMMANDS.map(({ label, command }) => (@@ -271,6 +273,9 @@ export default function Shell() {setShowPasteInput={setShowPasteInput}pasteInputRef={pasteInputRef}handlePasteInputEvent={handlePasteInputEvent}+ sendImage={sendImage}+ /* Opens upward — this bar is pinned to the bottom of the viewport. */+ popoverPlacement="above"/>)}</div>diff --git a/client/src/services/README.md b/client/src/services/README.mdindex de5f953c57..b516b9a58f 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -98,6 +98,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiGames.js` | Game studio records, managed-app binding, reusable sprite/music bindings, deterministic asset-bundle compilation/integrity preflight, and AI feedback history. || `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |+| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. || `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL. || `apiPipeline.js` | Pipeline (issues + stages + canon). |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 73f35297fa..32f1ea15d2 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -73,6 +73,7 @@ export * from './apiCreativeCommission.js';export * from './apiGames.js';export * from './apiMusicVideo.js';export * from './apiSprites.js';+export * from './apiShell.js';export * from './apiMoodBoard.js';export * from './apiThreejsModels.js';export * from './apiImporter.js';diff --git a/client/src/services/apiShell.js b/client/src/services/apiShell.jsnew file mode 100644index 0000000000..fddf678500--- /dev/null+++ b/client/src/services/apiShell.js@@ -0,0 +1,23 @@+import { request } from './apiCore.js';++/**+ * Hand a photo to whatever is running in a shell session — a live `claude`/`codex`+ * TUI reads the image off disk from the path the server pastes into its prompt.+ *+ * HTTP rather than the `shell:*` socket protocol: this is a one-shot request that+ * needs a result, and socket.io's 1MB frame limit can't carry a photo. Responds+ * with the STORED filename; the absolute path stays server-side.+ *+ * @param {string} sessionId+ * @param {{ data: string, filename: string, message?: string }} payload - base64+ * image bytes, the original name, and an optional accompanying message+ * @param {{ silent?: boolean }} [options] - `silent: true` when the caller owns+ * its own error UI (see the toasting convention in apiCore.js)+ * @returns {Promise<{ sessionId: string, filename: string }>}+ */+export const sendShellImage = (sessionId, { data, filename, message }, options = {}) =>+ request(`/shell/sessions/${encodeURIComponent(sessionId)}/image`, {+ method: 'POST',+ body: JSON.stringify({ data, filename, message }),+ ...options,+ });diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.jsindex 06fd392528..b678229b05 100644--- a/client/src/utils/fileUpload.js+++ b/client/src/utils/fileUpload.js@@ -81,6 +81,24 @@ export function readFileAsBase64(file) {});}+/**+ * Gate a picked file as an uploadable image: right kind, within the size cap.+ *+ * Every image picker in the app needs this pair of checks, and a surface that+ * PREVIEWS before uploading (the Shell photo composer) can't get it from+ * `processScreenshotUploads`, which uploads immediately. So it lives here and+ * both call it, keeping one wording for the size-limit message.+ *+ * @param {File} file+ * @param {number} [maxFileSize] - byte ceiling (default: the screenshot cap)+ * @returns {string|null} an error message, or null when the file is acceptable+ */+export function validateImageFile(file, maxFileSize = SCREENSHOT_MAX_FILE_SIZE) {+ if (!file?.type?.startsWith('image/')) return `File "${file?.name}" is not an image`;+ if (file.size > maxFileSize) return `File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`;+ return null;+}+/*** Process and upload image files as screenshots*@@ -101,12 +119,14 @@ export async function processScreenshotUploads(files, options = {}) {const fileArray = Array.from(files);for (const file of fileArray) {- // Skip non-image files silently+ // Non-image files are skipped SILENTLY here (this runs over a multi-select /+ // drop of mixed content, where naming each non-image is noise) — but an+ // oversized image is reported, since the user clearly meant to upload it.if (!file.type.startsWith('image/')) continue;- // Check file size- if (file.size > maxFileSize) {- onError?.(`File "${file.name}" exceeds the ${formatBytes(maxFileSize)} limit`);+ const problem = validateImageFile(file, maxFileSize);+ if (problem) {+ onError?.(problem);continue;}diff --git a/server/index.js b/server/index.jsindex c244298af0..1563c2cf1d 100644--- a/server/index.js+++ b/server/index.js@@ -26,6 +26,7 @@ import commandsRoutes from './routes/commands.js';import gitRoutes from './routes/git.js';import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';+import shellRoutes from './routes/shell.js';import attachmentsRoutes from './routes/attachments.js';import clientErrorsRoutes from './routes/clientErrors.js';import autoFixMetricsRoutes from './routes/autoFixMetrics.js';@@ -248,6 +249,7 @@ app.use('/api/commands', commandsRoutes);app.use('/api/git', gitRoutes);app.use('/api/usage', usageRoutes);app.use('/api/screenshots', screenshotsRoutes);+app.use('/api/shell', shellRoutes);app.use('/api/search', searchRoutes);app.use('/api/palette', paletteRoutes);app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex b0a28a23ca..07ae1b71f7 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1278,6 +1278,54 @@ export async function importFileToUploads(tempPath, originalName) {return importFileToDir(tempPath, originalName, PATHS.uploads);}+/**+ * Persist a base64-encoded IMAGE into `dir`, deriving the format from the bytes+ * rather than trusting the client: decode → size cap → magic-byte sniff → force+ * the extension to the detected format → sanitize + containment guard → write.+ *+ * This is the sibling of `saveBase64Upload` for the paths that must be certain+ * they wrote an image (they hand the file to an image-gen backend or to an agent+ * that will read it), so an extension allowlist isn't enough. Naming is the+ * CALLER's call — pass a name that is already unique if later uploads must not+ * overwrite this one, since `dir` is a shared bucket.+ *+ * Throws ServerError with the status/code/message contract `routes/screenshots.js`+ * established (`FILE_TOO_LARGE`, `INVALID_FILE_TYPE`, `INVALID_FILENAME` — all+ * 400) so callers keep their pinned responses.+ *+ * @param {string} dir - Destination directory (created if missing).+ * @param {{ filename: string, data: string }} upload - Desired base name (the+ * extension is replaced with the detected one) + base64 payload.+ * @param {{ maxBytes: number }} opts+ * @returns {Promise<{ filename: string, filePath: string, size: number,+ * format: string, mime: string }>}+ */+export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {+ const buffer = Buffer.from(data, 'base64');+ if (buffer.length > maxBytes) {+ throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });+ }++ const detected = detectImageFormat(buffer);+ if (!detected) {+ throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });+ }++ // The DETECTED extension wins over whatever the client claimed, so the file on+ // disk can't advertise a type its bytes contradict.+ const safeName = sanitizeFilename(filename);+ const fname = safeName.toLowerCase().endsWith(detected.ext) ? safeName : `${safeName}${detected.ext}`;+ const filePath = join(dir, fname);+ if (!isPathInsideDir(dir, filePath)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ await ensureDir(dir);+ await writeFile(filePath, buffer);++ return { filename: fname, filePath, size: buffer.length, format: detected.format, mime: detected.mime };+}+/*** Persist a base64-encoded upload into `dir` with the shared attachment* pipeline: extension allowlist → base64 decode → size cap → ensureDir →diff --git a/server/lib/uploadLimits.test.js b/server/lib/uploadLimits.test.jsindex adf9de1787..393f82abc3 100644--- a/server/lib/uploadLimits.test.js+++ b/server/lib/uploadLimits.test.js@@ -61,28 +61,52 @@ describe('uploadLimits', () => {// attachments.js drifted to unreachable 100MB/50MB claims. Discover the// routes rather than listing them, so a NEW upload route added later is// covered too — a hardcoded list would leave it unguarded.- // Detect the base64-in-JSON transport specifically — decoding a base64 body- // or handing one to saveBase64Upload. Routes that take RAW bytes via+ // Detect the base64-in-JSON transport specifically — decoding a base64 body,+ // or handing one to a shared saver. Routes that take RAW bytes via// express.raw() (imageClean.js) carry their own limit and are correctly out// of scope: no ×4/3 inflation applies to them.+ //+ // A route may also DELEGATE: `routes/shell.js` validates the body and hands it+ // to `services/shellImageDrop.js`, which calls the saver and owns the cap. So+ // each route is checked together with the services it imports — otherwise+ // moving the decode one file down silently exits this guard. Only the shared+ // savers count as a delegation signal, not a bare base64 decode: plenty of+ // services (mbox import, message sync) decode base64 that never came from a+ // client upload and have no business carrying an upload cap.const routesDir = join(HERE, '../routes');- const uploadRoutes = readdirSync(routesDir)- .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'))- .filter((f) => /Buffer\.from\([^)]*'base64'\)|saveBase64Upload/- .test(readFileSync(join(routesDir, f), 'utf8')));+ const SAVERS = /saveBase64Upload|saveImageUpload/;+ const INLINE_DECODE = /Buffer\.from\([^)]*'base64'\)/;+ const readSafe = (p) => { try { return readFileSync(p, 'utf8'); } catch { return ''; } };++ const routeFiles = readdirSync(routesDir)+ .filter((f) => f.endsWith('.js') && !f.endsWith('.test.js'));++ const uploadRoutes = routeFiles.map((f) => {+ const src = readFileSync(join(routesDir, f), 'utf8');+ // The route's own service imports, read so a delegated saver is visible.+ const delegates = [...src.matchAll(/from '\.\.\/services\/([\w/.-]+\.js)'/g)]+ .map((m) => ({ name: `services/${m[1]}`, src: readSafe(join(HERE, '../services', m[1])) }))+ .filter((s) => SAVERS.test(s.src));+ return { name: f, src, delegates };+ }).filter((r) => INLINE_DECODE.test(r.src) || SAVERS.test(r.src) || r.delegates.length > 0);+expect(uploadRoutes.length, 'no upload routes discovered — did the detection heuristic break?')- .toBeGreaterThanOrEqual(4);+ .toBeGreaterThanOrEqual(5);for (const route of uploadRoutes) {- const src = readFileSync(join(routesDir, route), 'utf8');- // Assert the route USES a shared constant (positive), rather than+ // The cap may live in the route or in the service it delegates to; assert+ // one of them USES a shared constant (positive), rather than// pattern-matching for the absence of one literal spelling — a route// could hardcode `= 52428800` under any name and slip past that.- expect(src, `${route} must take its cap from lib/uploadLimits.js`)- .toMatch(/MAX_BASE64_UPLOAD_BYTES|MAX_SCREENSHOT_BYTES/);- // Belt-and-braces: no raw MB-shaped byte literal left in an upload route.- expect(src, `${route} still hardcodes a raw byte cap`)- .not.toMatch(/=\s*\d+\s*\*\s*1024\s*\*\s*1024/);+ const chain = [{ name: route.name, src: route.src }, ...route.delegates];+ const where = chain.map((f) => f.name).join(' / ');+ expect(chain.some((f) => /MAX_BASE64_UPLOAD_BYTES|MAX_SCREENSHOT_BYTES/.test(f.src)),+ `${where} must take its cap from lib/uploadLimits.js`).toBe(true);+ // Belt-and-braces: no raw MB-shaped byte literal left anywhere on the path.+ for (const file of chain) {+ expect(file.src, `${file.name} still hardcodes a raw byte cap`)+ .not.toMatch(/=\s*\d+\s*\*\s*1024\s*\*\s*1024/);+ }}});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 54345ca2f1..2837db3e54 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -818,6 +818,21 @@ export function validateRequest(schema, data) {});}+// =============================================================================+// SHELL+// =============================================================================++// POST /api/shell/sessions/:sessionId/image — hand a photo to whatever is running+// in a shell session. `data` is base64 image bytes; the real ceiling is enforced+// by `saveImageUpload` (MAX_SCREENSHOT_BYTES) against the DECODED buffer, so the+// cap here only refuses a payload too large to be worth decoding. The message cap+// matches the BTW route's — both end up bracket-pasted into the same TUI prompt.+export const shellImageDropSchema = z.object({+ data: z.string().min(1, 'data is required (base64)').max(64 * 1024 * 1024),+ filename: z.string().min(1, 'filename is required').max(255),+ message: z.string().max(5000).optional()+});+// =============================================================================// CLIENT ERROR REPORT// =============================================================================diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex 8f55cbe01c..5ad00bf374 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -1,10 +1,9 @@import { Router } from 'express';-import { writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { join, resolve } from 'path';+import { resolve } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { ensureDir, PATHS, sanitizeFilename, isPathInsideDir } from '../lib/fileUtils.js';+import { PATHS, sanitizeFilename, isPathInsideDir, saveImageUpload } from '../lib/fileUtils.js';import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';const SCREENSHOTS_DIR = PATHS.screenshots;@@ -14,84 +13,31 @@ const router = Router();// Screenshots cap well below the wire limit on purpose — see lib/uploadLimits.js.const MAX_FILE_SIZE = MAX_SCREENSHOT_BYTES;-/**- * Validate image magic bytes- * Note: This validates the file signature/magic bytes at the start of the file.- * It does NOT validate the entire file structure - a file could have valid magic- * bytes but malformed content. This is sufficient for basic type detection and- * blocking non-image uploads. For high-security scenarios, consider using a- * proper image processing library to fully validate the file structure.- */-function isValidImage(buffer) {- if (buffer.length < 12) return null; // Too small to be a valid image- // PNG: 89 50 4E 47- if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) {- return 'png';- }- // JPEG: FF D8 FF- if (buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {- return 'jpg';- }- // GIF: 47 49 46 38- if (buffer[0] === 0x47 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x38) {- return 'gif';- }- // WebP: 52 49 46 46 ... 57 45 42 50- if (buffer[0] === 0x52 && buffer[1] === 0x49 && buffer[2] === 0x46 && buffer[3] === 0x46 &&- buffer[8] === 0x57 && buffer[9] === 0x45 && buffer[10] === 0x42 && buffer[11] === 0x50) {- return 'webp';- }- return null;-}-// POST /api/screenshots - Upload a screenshot (base64)router.post('/', asyncHandler(async (req, res) => {- const { data, filename, mimeType } = req.body;+ const { data, filename } = req.body;if (!data) {throw new ServerError('data is required (base64)', { status: 400, code: 'VALIDATION_ERROR' });}- // Decode base64 and validate size- const buffer = Buffer.from(data, 'base64');- if (buffer.length > MAX_FILE_SIZE) {- throw new ServerError(`File exceeds maximum size of ${MAX_FILE_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });- }-- // Validate actual file content (magic bytes)- const detectedType = isValidImage(buffer);- if (!detectedType) {- throw new ServerError('Invalid image file - only PNG, JPEG, GIF, and WebP are supported', { status: 400, code: 'INVALID_FILE_TYPE' });- }-- // Ensure screenshots directory exists- if (!existsSync(SCREENSHOTS_DIR)) {- await ensureDir(SCREENSHOTS_DIR);- }-const id = uuidv4();- const ext = detectedType; // Use detected type, not client-provided- // Sanitize user-provided filename or generate a safe one- const safeName = filename ? sanitizeFilename(filename) : `screenshot-${id}.${ext}`;- // Ensure extension matches detected type- const fname = safeName.endsWith(`.${ext}`) ? safeName : `${safeName}.${ext}`;- const filepath = join(SCREENSHOTS_DIR, fname);-- // Double-check path is within screenshots directory (defense in depth)- if (!isPathInsideDir(SCREENSHOTS_DIR, filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- await writeFile(filepath, buffer);+ // Shared pipeline: decode → size cap → magic-byte sniff → detected extension →+ // containment guard → write. The client-supplied mimeType is deliberately+ // ignored; the bytes decide the type.+ const saved = await saveImageUpload(SCREENSHOTS_DIR, {+ filename: filename || `screenshot-${id}`,+ data,+ }, { maxBytes: MAX_FILE_SIZE });- console.log(`📸 Screenshot saved: ${fname} (${buffer.length} bytes)`);+ console.log(`📸 Screenshot saved: ${saved.filename} (${saved.size} bytes)`);res.json({id,- filename: fname,+ filename: saved.filename,// API-relative URL only — never the absolute FS path (leaks install layout).- path: `/api/screenshots/${encodeURIComponent(fname)}`,- size: buffer.length+ path: `/api/screenshots/${encodeURIComponent(saved.filename)}`,+ size: saved.size});}));diff --git a/server/routes/shell.js b/server/routes/shell.jsnew file mode 100644index 0000000000..bb95ad5604--- /dev/null+++ b/server/routes/shell.js@@ -0,0 +1,35 @@+/**+ * Shell session HTTP routes.+ *+ * The Shell page drives its PTY over Socket.IO (`shell:input` / `shell:output` /+ * `shell:attach` — a keystroke stream and a fan-out, which is what sockets are+ * for). This module is for the shell operations that are one-shot REQUESTS with a+ * result and a payload too big for a socket frame — currently just handing a photo+ * to whatever is running in a session, which is the same shape as+ * `POST /api/cos/agents/:id/btw` and gets the same treatment: Zod validation,+ * `asyncHandler`, and ServerErrors bubbling to the centralized middleware.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, shellImageDropSchema } from '../lib/validation.js';+import { dropImageIntoShellSession } from '../services/shellImageDrop.js';++const router = Router();++// POST /api/shell/sessions/:sessionId/image — save a photo and paste its path+// (plus an optional message) into the session, so a running agent can read it.+router.post('/sessions/:sessionId/image', asyncHandler(async (req, res) => {+ const { data, filename, message } = validateRequest(shellImageDropSchema, req.body ?? {});+ // The service throws a ServerError — 404 when the session is gone, 400 when the+ // bytes are oversized or not a supported image — so no result-shape mapping here.+ const result = await dropImageIntoShellSession({+ sessionId: req.params.sessionId,+ filename,+ data,+ message,+ });+ res.json(result);+}));++export default router;diff --git a/server/routes/shell.test.js b/server/routes/shell.test.jsnew file mode 100644index 0000000000..448203cec1--- /dev/null+++ b/server/routes/shell.test.js@@ -0,0 +1,121 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { rmSync, readFileSync, readdirSync } from 'fs';+import { dirname, join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Point the screenshots root at a throwaway temp dir but keep every real helper+// (saveImageUpload, sanitizeFilename, detectImageFormat, ...) so this exercises+// the actual save pipeline, not a mock of it. Created inside the hoisted factory+// to avoid a TDZ on an outer const.+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join: j } = await import('path');+ const root = mkdtempSync(j(tmpdir(), 'portos-shell-image-'));+ return { ...actual, PATHS: { ...actual.PATHS, screenshots: j(root, 'screenshots') } };+});++// The PTY registry is the one thing worth faking — a real shell session would+// spawn a process just to assert what got written to it.+vi.mock('../services/shell.js', () => ({+ getSession: vi.fn(),+ pasteToSession: vi.fn(() => true),+}));++import { PATHS } from '../lib/fileUtils.js';+import { getSession, pasteToSession } from '../services/shell.js';+import shellRoutes from './shell.js';++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '20mb' }));+ app.use('/api/shell', shellRoutes);+ app.use(errorMiddleware);+ return app;+};++const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d]);+const pngBase64 = PNG_BYTES.toString('base64');+const SESSION = 'sess-abcdef123456';+const post = (body) => request(buildApp()).post(`/api/shell/sessions/${SESSION}/image`).send(body);++beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(getSession).mockReturnValue({ _id: 'sess-abc' });+ vi.mocked(pasteToSession).mockReturnValue(true);+});++afterAll(() => rmSync(dirname(PATHS.screenshots), { recursive: true, force: true }));++describe('POST /api/shell/sessions/:sessionId/image', () => {+ it('writes the bytes and pastes message + absolute path into the session', async () => {+ const res = await post({ data: pngBase64, filename: 'photo.png', message: 'what is this?' });++ expect(res.status).toBe(200);+ expect(res.body.sessionId).toBe(SESSION);+ expect(res.body.filename).toMatch(/^shell-[0-9a-f]{8}-photo\.png$/);+ // The absolute path is never in the response — it would leak the install layout.+ expect(JSON.stringify(res.body)).not.toContain(PATHS.screenshots);++ const stored = join(PATHS.screenshots, res.body.filename);+ expect(readFileSync(stored)).toEqual(PNG_BYTES);+ expect(pasteToSession).toHaveBeenCalledWith(SESSION, `what is this?\n${stored}`, { label: 'image drop' });+ });++ it('pastes the bare path when no message is given', async () => {+ const res = await post({ data: pngBase64, filename: 'photo.png' });+ expect(res.status).toBe(200);+ expect(pasteToSession).toHaveBeenCalledWith(+ SESSION,+ join(PATHS.screenshots, res.body.filename),+ { label: 'image drop' },+ );+ });++ it('uniquifies the stored name so a repeated camera-roll name cannot overwrite', async () => {+ const before = readdirSync(PATHS.screenshots).length;+ const a = await post({ data: pngBase64, filename: 'IMG_0001.png' });+ const b = await post({ data: pngBase64, filename: 'IMG_0001.png' });+ expect(a.body.filename).not.toBe(b.body.filename);+ // Two distinct files on disk, not one overwritten twice.+ expect(readdirSync(PATHS.screenshots).length - before).toBe(2);+ });++ it('404s without writing anything when the session is gone', async () => {+ vi.mocked(getSession).mockReturnValue(null);+ const before = readdirSync(PATHS.screenshots).length;+ const res = await post({ data: pngBase64, filename: 'photo.png' });+ expect(res.status).toBe(404);+ expect(readdirSync(PATHS.screenshots)).toHaveLength(before);+ expect(pasteToSession).not.toHaveBeenCalled();+ });++ it('rejects bytes that are not a supported image', async () => {+ const res = await post({ data: Buffer.from('not an image at all').toString('base64'), filename: 'photo.png' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_FILE_TYPE');+ expect(pasteToSession).not.toHaveBeenCalled();+ });++ // The extension comes from the bytes, so a mislabelled upload can't land on disk+ // advertising a type it isn't.+ it('stores a PNG as .png even when the client claims .jpg', async () => {+ const res = await post({ data: pngBase64, filename: 'photo.jpg' });+ expect(res.body.filename.endsWith('.png')).toBe(true);+ });++ it('400s on a missing payload', async () => {+ const res = await post({ filename: 'photo.png' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });++ it('400s on an over-long message', async () => {+ const res = await post({ data: pngBase64, filename: 'photo.png', message: 'x'.repeat(5001) });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ });+});diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 3f3359c222..61a9584de0 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -429,17 +429,7 @@ export async function sendBtwToAgent(agentId, message) {// Bracketed-paste + delayed Enter, mirroring the initial prompt paste in// agentTuiSpawning.js: Claude Code commits the paste buffer before the// submit arrives, so multi-line messages land as a single paste event.- shellService.writeToSession(agentInfo.tuiSessionId, `\x1b[200~${message}\x1b[201~`);- setTimeout(() => {- try {- // Re-check session liveness: the TUI session may have died in the 400ms window.- if (shellService.getSession(agentInfo.tuiSessionId)) {- shellService.writeToSession(agentInfo.tuiSessionId, '\r');- }- } catch (err) {- console.error(`❌ [cosAgents] BTW delayed Enter failed for session ${agentInfo.tuiSessionId}: ${err.message}`);- }- }, 400);+ shellService.pasteToSession(agentInfo.tuiSessionId, message, { label: '[cosAgents] BTW' });// Track in agent state (cap at 50 messages)const timestamp = new Date().toISOString();diff --git a/server/services/shell.js b/server/services/shell.jsindex 03d26bfdce..f61b020d90 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -546,6 +546,48 @@ export function writeToSession(sessionId, data) {return false;}+// Gap between the bracketed paste and the Enter that submits it. Claude Code+// commits its paste buffer asynchronously, so an Enter in the same tick arrives+// before the buffer is committed and submits nothing.+const PASTE_SUBMIT_DELAY_MS = 400;++/**+ * Deliver `text` to a session as a SINGLE bracketed-paste event, then submit it+ * with a delayed Enter.+ *+ * This is how you hand a message to a live agent TUI rather than to a shell:+ * Claude Code reads `ESC[200~…ESC[201~` as one paste, so a multi-line message+ * lands as one input event instead of N submits.+ *+ * Scope: this is the ONE-SHOT form, for short payloads that don't need+ * confirmation. A large paste that must be *verified* to have landed (an agent's+ * initial prompt) goes through `lib/tuiHandshake.js` instead — its+ * `scheduleSubmitEnters` sends repeated Enters because a single `\r` can be+ * swallowed while the TUI is still reflowing a big paste, and `attemptPaste` in+ * `agentTuiSpawning.js` retries against a paste-marker probe. Don't grow this+ * function into that; reach for those.+ *+ * @param {string} sessionId+ * @param {string} text - paste payload (no trailing newline; the Enter submits it)+ * @param {object} [opts]+ * @param {string} [opts.label='paste'] - log label for the delayed-Enter failure path+ * @returns {boolean} false when the session is unknown (nothing was written)+ */+export function pasteToSession(sessionId, text, { label = 'paste' } = {}) {+ if (!writeToSession(sessionId, `\x1b[200~${text}\x1b[201~`)) return false;+ setTimeout(() => {+ try {+ // writeToSession no-ops if the PTY died inside the window. try/catch still+ // earns its place: a write to a live-but-broken pty can throw, and this+ // runs outside the request lifecycle where that would crash the process.+ writeToSession(sessionId, '\r');+ } catch (err) {+ console.error(`🐚 ${label} delayed Enter failed for ${sessionId.slice(0, 8)}: ${err.message}`);+ }+ }, PASTE_SUBMIT_DELAY_MS);+ return true;+}+/*** When input was last written to this session (human paste/keystrokes via* `shell:input`, or an internal writer like the CoS agent's auto-paste) — ordiff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex bd0f601f5e..cbecd1fca7 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -372,6 +372,38 @@ describe('writeToSession / resizeSession', () => {});});+describe('pasteToSession', () => {+ let id;+ let pty;+ beforeEach(() => {+ vi.useFakeTimers();+ id = shell.createShellSession(makeSocket());+ pty = ptyInstances[0];+ });++ it('writes one bracketed paste, then submits with a delayed Enter', () => {+ expect(shell.pasteToSession(id, 'line one\nline two')).toBe(true);+ // The paste is a SINGLE write — a multi-line message must not become N submits.+ expect(pty.write).toHaveBeenCalledWith('\x1b[200~line one\nline two\x1b[201~');+ expect(pty.write).not.toHaveBeenCalledWith('\r');++ vi.advanceTimersByTime(400);+ expect(pty.write).toHaveBeenCalledWith('\r');+ });++ it('skips the delayed Enter when the session dies inside the window', () => {+ shell.pasteToSession(id, 'hi');+ shell.killSession(id);+ vi.advanceTimersByTime(400);+ expect(pty.write).not.toHaveBeenCalledWith('\r');+ });++ it('returns false and writes nothing for a missing session', () => {+ expect(shell.pasteToSession('missing', 'hi')).toBe(false);+ expect(pty.write).not.toHaveBeenCalled();+ });+});+describe('killSession', () => {it('kills the PTY, removes the session, fires the onExit hook, broadcasts', async () => {const onExit = vi.fn();diff --git a/server/services/shellImageDrop.js b/server/services/shellImageDrop.jsnew file mode 100644index 0000000000..eed9698cdf--- /dev/null+++ b/server/services/shellImageDrop.js@@ -0,0 +1,81 @@+/**+ * Shell image drop — hand a photo to whatever is running in a shell session (a+ * live `claude` / `codex` TUI, or a bare prompt).+ *+ * Agent CLIs read images off disk, so the way to actually get a photo in front of+ * one is to put the file's absolute path into its prompt. This module owns that+ * translation: it persists the uploaded bytes, then bracket-pastes+ * `<message>\n<absolute path>` into the session so the agent sees one input event.+ *+ * The path never leaves the server — the API answers with the stored filename+ * only, so a response can't leak the install layout.+ *+ * Storage is `PATHS.screenshots`, the existing "user-supplied image an AI reads+ * off disk" bucket (shared with the vision-test and universe-describe paths, and+ * already archivable/deletable via dataManager). Because it IS shared, the name+ * is uniquified here: a phone camera roll hands out the same `IMG_0001.jpg` over+ * and over, and a second drop must not overwrite bytes the agent hasn't read yet.+ */++import { PATHS, saveImageUpload } from '../lib/fileUtils.js';+import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';+import { ServerError } from '../lib/errorHandler.js';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { getSession, pasteToSession } from './shell.js';++/**+ * Compose the text pasted into the session.+ *+ * The message comes first and the path lands on its own line, so a model reads it+ * as "here's the ask, here's the file". Paths containing whitespace are+ * single-quoted (POSIX-escaped): the filename can't contain whitespace after+ * `sanitizeFilename`, but the install root can.+ *+ * @param {string} imagePath - absolute path to the saved image+ * @param {string} [message] - optional accompanying message+ * @returns {string} paste payload (no trailing newline — the Enter submits it)+ */+export function buildImageDropText(imagePath, message = '') {+ const trimmed = typeof message === 'string' ? message.trim() : '';+ const pathRef = /\s/.test(imagePath)+ ? `'${imagePath.replace(/'/g, "'\\''")}'`+ : imagePath;+ return trimmed ? `${trimmed}\n${pathRef}` : pathRef;+}++/**+ * Save an uploaded image and paste it (plus an optional message) into a live+ * shell session.+ *+ * The session is checked BEFORE the bytes are written so a stale session id+ * doesn't leave an orphan file on disk.+ *+ * @param {object} params+ * @param {string} params.sessionId - target shell session+ * @param {string} params.filename - client-supplied name (used for the stored+ * name's readable suffix only; the extension comes from the bytes)+ * @param {string} params.data - base64-encoded image bytes+ * @param {string} [params.message] - message to send alongside the image+ * @returns {Promise<{ sessionId: string, filename: string }>} the STORED filename+ * @throws {ServerError} 404 when the session is gone; 400 from `saveImageUpload`+ * when the bytes are too large or aren't a supported image+ */+export async function dropImageIntoShellSession({ sessionId, filename, data, message = '' }) {+ if (!getSession(sessionId)) {+ throw new ServerError('Session not found', { status: 404, code: 'NOT_FOUND' });+ }++ const saved = await saveImageUpload(PATHS.screenshots, {+ filename: `shell-${uuidv4().slice(0, 8)}-${filename}`,+ data,+ }, { maxBytes: MAX_SCREENSHOT_BYTES });++ // Re-check liveness: the PTY can exit while the bytes are being written.+ if (!pasteToSession(sessionId, buildImageDropText(saved.filePath, message), { label: 'image drop' })) {+ throw new ServerError('Session not found', { status: 404, code: 'NOT_FOUND' });+ }++ console.log(`🖼️ Sent image ${saved.filename} to shell session ${sessionId.slice(0, 8)}`);++ return { sessionId, filename: saved.filename };+}diff --git a/server/services/shellImageDrop.test.js b/server/services/shellImageDrop.test.jsnew file mode 100644index 0000000000..866adf554f--- /dev/null+++ b/server/services/shellImageDrop.test.js@@ -0,0 +1,95 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./shell.js', () => ({+ getSession: vi.fn(),+ pasteToSession: vi.fn(() => true),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { screenshots: '/opt/portos/data/screenshots' },+ saveImageUpload: vi.fn(),+}));++import { buildImageDropText, dropImageIntoShellSession } from './shellImageDrop.js';+import { getSession, pasteToSession } from './shell.js';+import { saveImageUpload, PATHS } from '../lib/fileUtils.js';++const SESSION_ID = 'session-abcdef123456';+const STORED = 'shell-aa11bb22-photo.jpg';+const IMAGE_PATH = `${PATHS.screenshots}/${STORED}`;+const upload = { sessionId: SESSION_ID, filename: 'photo.jpg', data: 'Zm9v' };++beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.mocked(getSession).mockReturnValue({ _id: 'session-' });+ vi.mocked(pasteToSession).mockReturnValue(true);+ vi.mocked(saveImageUpload).mockResolvedValue({ filename: STORED, filePath: IMAGE_PATH, size: 3 });+});++describe('buildImageDropText', () => {+ it('preserves a multi-line message as one payload', () => {+ expect(buildImageDropText('/tmp/a.png', 'first\nsecond'))+ .toBe('first\nsecond\n/tmp/a.png');+ });++ it('treats a whitespace-only message as no message', () => {+ expect(buildImageDropText('/tmp/a.png', ' ')).toBe('/tmp/a.png');+ });++ it('single-quotes a path containing whitespace', () => {+ expect(buildImageDropText('/tmp/my shots/a.png', 'look'))+ .toBe("look\n'/tmp/my shots/a.png'");+ });++ it('escapes an embedded single quote POSIX-style', () => {+ expect(buildImageDropText("/tmp/adam's shots/a.png"))+ .toBe("'/tmp/adam'\\''s shots/a.png'");+ });+});++describe('dropImageIntoShellSession', () => {+ it('saves the image and pastes message + absolute path, answering with the stored name', async () => {+ const result = await dropImageIntoShellSession({ ...upload, message: 'describe this' });++ // The stored name is uniquified — a phone camera roll repeats `IMG_0001.jpg`,+ // and a second drop must not overwrite bytes the agent hasn't read yet.+ expect(saveImageUpload).toHaveBeenCalledWith(+ PATHS.screenshots,+ { filename: expect.stringMatching(/^shell-[0-9a-f]{8}-photo\.jpg$/), data: 'Zm9v' },+ { maxBytes: expect.any(Number) },+ );+ expect(pasteToSession).toHaveBeenCalledWith(+ SESSION_ID,+ `describe this\n${IMAGE_PATH}`,+ { label: 'image drop' },+ );+ // The absolute path must never come back over the wire.+ expect(result).toEqual({ sessionId: SESSION_ID, filename: STORED });+ });++ it('pastes the bare path when there is no message', async () => {+ await dropImageIntoShellSession(upload);+ expect(pasteToSession).toHaveBeenCalledWith(SESSION_ID, IMAGE_PATH, { label: 'image drop' });+ });++ // Checking the session first means a stale id can't leave an orphan file behind.+ it('404s before writing anything when the session is gone', async () => {+ vi.mocked(getSession).mockReturnValue(null);+ await expect(dropImageIntoShellSession(upload)).rejects.toThrow('Session not found');+ expect(saveImageUpload).not.toHaveBeenCalled();+ expect(pasteToSession).not.toHaveBeenCalled();+ });++ it('404s when the session dies while the bytes are being written', async () => {+ vi.mocked(pasteToSession).mockReturnValue(false);+ await expect(dropImageIntoShellSession(upload)).rejects.toThrow('Session not found');+ });++ // saveImageUpload owns the size cap and the magic-byte sniff; its 400 bubbles.+ it('lets a rejected upload bubble instead of pasting', async () => {+ vi.mocked(saveImageUpload).mockRejectedValue(new Error('Invalid image file'));+ await expect(dropImageIntoShellSession(upload)).rejects.toThrow('Invalid image file');+ expect(pasteToSession).not.toHaveBeenCalled();+ });+});