Skip to content

Commit a67b0c3

Browse files
naohito2000Naohito YoshikawaShotaroKataoka
authored
feat: Web-first local mode (Next.js API routes + kiro-cli ACP) (#87)
* 📋 spec(local-desktop-app): add requirements, design, tasks, notes * ✨ feat(local-desktop-app): Task 1-2 prompt extraction + kiro-cli agent configs - Extract system prompt to prompts/system-prompt.md - agent/basic_agent.py reads from prompts/ with inline fallback - Add .kiro/agents/sdpm-spec.json (SPEC agent with subagent + hooks) - Add .kiro/agents/sdpm-composer.json (Composer agent, no user interaction) - Add desktop/scripts/auto-build.py (postToolUse hook for slide edit) * ✨ feat(local-desktop-app): Task 3 Tauri project shell - Tauri 2 + Vite + React project in desktop/ - Shell plugin with spawn/stdin-write permissions for kiro-cli acp - Vite alias @ → web-ui/src/ for shared component imports - Minimal App placeholder with globals.css import * ✨ feat(local-desktop-app): Task 4 ACP bridge service - acpAgentService.ts: spawn kiro-cli acp, JSON-RPC over stdin/stdout - Same invokeAgent() signature as agentCoreService.js for ChatPanel compat - ACP notifications → onStreamUpdate/onToolUse callbacks - session/new, session/prompt, session/cancel support * ✨ feat(local-desktop-app): Task 5-6 local deck + upload services - localDeckService.ts: filesystem CRUD, convertFileSrc for preview URLs - localUploadService.ts: local file copy to deck workspace - Web-only features stubbed as no-ops (share, public, search) * ✨ feat(local-desktop-app): Task 7 service provider + desktop entry point - ServiceProvider: resolves local services for desktop app - main.tsx: loads DecksPage with ServiceProvider instead of AuthProvider - Notes: identified useAuth() shim need and service import aliasing challenge * 🔧 fix(local-desktop-app): Vite alias for auth shim + service overrides - authShim.ts: replaces react-oidc-context (useAuth, useAutoSignin) - useAuthShim.ts: replaces @/hooks/useAuth (AppShell wrapper) - vite.config.ts: alias order — specific service/auth overrides before @ catch-all - Web version completely unaffected — all changes in desktop/ * ✨ feat(local-desktop-app): Task 8-9 LibreOffice install + Tauri build CI - install-libreoffice.sh/ps1: auto-install via brew/apt/choco/winget - lib.rs: startup LibreOffice check with warning - build-desktop.yml: GitHub Actions for macOS/Linux/Windows builds - Triggered on desktop-v* tags or manual dispatch * 🐛 fix(local-desktop-app): Tailwind CSS + PostCSS setup for desktop - Add postcss.config.mjs with @tailwindcss/postcss - app.css: @source directives for web-ui + desktop component scanning - main.tsx: import both app.css (source) and globals.css (styles) - Install shared web-ui dependencies (sonner, lucide-react, radix, etc.) - Fix localUploadService circular re-export - Fix acpAgentService export names (invokeAgentCore alias) - Generate Tauri icons from web-ui/public/icon-512.png * 🐛 fix(local-desktop-app): merge globals.css into app.css for single Tailwind context - @import tailwindcss + @source + theme + custom styles all in one file - Fixes utility classes (flex, grid, gap) not being generated - CSS output: 26KB → 107KB (full Tailwind utilities now included) * 📝 notes: document globals.css duplication trade-off * 🐛 fix(local-desktop-app): fix file:// prompt path in agent configs * 🔧 fix(local-desktop-app): add Tauri FS plugin + permissions - Add tauri-plugin-fs to Cargo.toml and lib.rs - Add FS permissions scoped to ~/Documents/SDPM-Presentations/ * 🐛 fix(local-desktop-app): add dummy aws-exports.json + fix FS permissions - ChatPanel requires /aws-exports.json to set configLoaded=true - Add desktop/public/aws-exports.json with local dummy values - Simplify Tauri FS permissions (scope-home-recursive) * 🐛 fix(local-desktop-app): add mcpServers:[] to session/new + fix cwd path - session/new requires mcpServers field (array, not object) - Fix homeDir trailing slash handling - Add cwd option to spawn kiro-cli from project root * ✨ feat(local-desktop-app): ACP chat working end-to-end - Fix session/update event parsing (sessionUpdate field, not type) - Fix prompt format (array, not string) - Fix mcpServers required in session/new - Fix turnEnd: use rpcRequest resolution instead of separate promise - Chat with kiro-cli agent now works in Tauri desktop app * 📝 notes: document ACP protocol field names and gotchas * 🐛 fix(local-desktop-app): resolve project root via Tauri command - Add get_project_root Rust command that finds project root by looking for prompts/ or .kiro/agents/ - kiro-cli spawned with cwd=project root so .kiro/agents/sdpm-spec.json is found * 🐛 fix(local-desktop-app): fix ACP tool event field names - tool_call (not tool_use), toolCallId (not toolUseId), title (not name) - Handle tool_call_update with correct field mapping * 🐛 fix(local-desktop-app): add mcp-local as MCP server to agent configs - sdpm MCP server provides init_presentation, read_workflows, run_python, generate_pptx, measure, preview etc. - Agent can now follow the same workflow as web version - Both sdpm-spec and sdpm-composer connect to mcp-local/server.py * 📝 checkpoint: ACP chat + mcp-local working, UI integration pending * 🐛 fix(local-desktop-app): tool completion detection + presentation.json support - Parse ACP tool_call_update rawOutput to extract result - Derive deckId from output_dir for onDeckCreated callback - Support both deck.json and presentation.json in localDeckService - listDecks scans directories directly instead of requiring decks.json index - patchDeck supports both file formats * 📝 notes: document mcp-local/mcp-server tool parity gap as blocker - run_python missing in mcp-local (critical) - get_preview API mismatch - save_web_image, apply_style, read_uploaded_file missing - Plan: separate branch feat/mcp-local-parity from main * ✨ feat(mcp-local): add run_python tool for local code execution - Execute Python code with cwd set to deck directory - No sandbox (direct subprocess execution) - measure_slides support via existing measure tool - API compatible with mcp-server's run_python (deck_id, save, measure_slides, purpose) * 🐛 fix(mcp-local): align instructions with mcp-server - Add run_python architecture guidance to MCP instructions - Agent now knows to use run_python for file editing, not fs_write - Match mcp-server's single workflow entry point * 🐛 fix(local-desktop-app): fix infinite re-render + stable collaborators ref - Add stable empty array/object refs for collaborators in getDeck - Prevents DeckActions useEffect infinite loop - Support presentation.json in getDeck/patchDeck/listDecks * 🔍 debug: add tool completion log for deckId detection * 🐛 fix(local-desktop-app): disable Vite browser open + read art-direction.md fallback * ✨ feat(local-desktop-app): implement fetchStyles from local style HTML files - Read style HTML from skill/references/examples/styles/ - fetchStyleHtml returns full HTML for style preview - Art direction step now shows style candidates in SpecStepNav * 🐛 fix(local-desktop-app): keep isLoading=true until turn ends - Don't await rpcRequest for session/prompt (it resolves on stopReason) - Use turnEnd promise to keep invokeAgent pending until agent finishes - Stop button now visible during agent execution - Fix beforeDevCommand to prevent browser auto-open * 🐛 fix: disable vite auto-open in package.json dev script * 🐛 fix: prevent agent from opening files in external browser - Add instruction to not use open/xdg-open/start commands - Art direction HTML should be displayed in UI, not opened externally * 🐛 fix: move no-open rule to kiro agent config only - Revert system-prompt.md (shared with web version) - Add desktop-only rule to sdpm-spec.json prompt * 🐛 fix(mcp-local): remove open_styles_gallery from list_styles - Was opening browser with styles HTML gallery - Desktop app displays styles in UI instead * 🐛 fix(local-desktop-app): only resolve turnEnd on end_turn, not tool_use - stopReason 'tool_use' means agent will continue after tool result - Only 'end_turn' means the agent is done - Keeps isLoading=true during multi-tool agent turns * 🐛 fix: remove --open false from vite CLI (was parsed as URL) * 🐛 fix(local-desktop-app): catch end_turn from both pending and unmatched responses - Check stopReason on pending response resolution too - Handles case where kiro-cli reuses/increments response ids * 🐛 fix(local-desktop-app): send session/cancel as notification, not request - cancel was consuming a request id, causing prompt response to be missed - Send cancel directly without id (fire-and-forget) * 🐛 fix(local-desktop-app): treat cancelled as turn end - stopReason 'cancelled' also resolves turnEnd promise - Allows chat to continue after stopping agent * 🐛 fix(local-desktop-app): restrict agent tools to @sdpm MCP only - Remove fs_read, fs_write, execute_bash, grep, glob from agent tools - Agent can only use MCP tools → forced to follow workflow like web version - Prevents agent from bypassing workflow with generic file tools * 🐛 fix(local-desktop-app): enforce workflow-first in agent prompt - Add MANDATORY First Step: read_workflows before any other tool - Matches web version behavior where workflow is always read first * 🐛 fix(local-desktop-app): embed MCP instructions in agent prompt - Web version injects MCP instructions into system prompt directly - kiro-cli treats MCP instructions as lower priority - Embed the same instructions in agent prompt for equal priority * ✨ feat(local-desktop-app): reset ACP session on New Chat - Track currentChatSessionId to detect when UI creates new chat - Create new ACP session (session/new) while reusing same kiro-cli process - Agent context is fresh for each new chat * ✨ feat(local-desktop-app): auto-approve permission requests from kiro-cli - Handle session/request_permission by replying allow_always - Subagent and tool permissions auto-approved * 🐛 fix(local-desktop-app): clarify agent role - do Phase 1 yourself, don't delegate - Explicitly state 'You ARE the SPEC agent' - Only use subagent for Phase 2 after user approval - Enforce read_workflows as first action * 🐛 fix(local-desktop-app): simplify agent prompt to match web version - Remove all custom instructions from prompt - Use only system-prompt.md (same as web version) - Let MCP instructions be handled by kiro-cli natively * 🐛 fix(local-desktop-app): inline web version's effective prompt - Embed system-prompt.md + MCP instructions directly in agent prompt - Matches exactly what web version's agent sees as system prompt - kiro-cli doesn't inject MCP instructions into system prompt like web version does * 🐛 fix(local-desktop-app): normalize tool_call name + pass rawInput as input - Strip 'Running: @sdpm/' prefix from tool_call title - Pass rawInput as input for workflow phase detection - Enables onWorkflowPhase to detect briefing/outline/art-direction transitions * ✨ feat(mcp-local): add apply_style tool + document dual maintenance - apply_style copies style HTML to deck's specs/art-direction.html - Matches mcp-server's apply_style functionality - Document unavoidable dual maintenance (prompt, CSS) in notes * 🐛 fix(local-desktop-app): filter session/update by sessionId - Only process messages from our ACP session - Ignore subagent session messages (different sessionId) - Prevents subagent output from appearing in parent chat * ✨ feat(local-desktop-app): forward subagent tool events to parent ToolCard - Track subagentToolCallId when 'Spawning agent crew' starts - Forward subagent tool_call/tool_call_update as toolStream to parent - Shows subagent progress (run_python, grid, measure) in compose ToolCard * ✨ feat(local-desktop-app): add parallel subagent instructions to SPEC agent - Instruct SPEC agent to split slides into groups (max 4) - Provide InvokeSubagents JSON example with multiple sdpm-composer entries - Group assignment rules from feat/agent-separation-spec-composer branch * 📝 checkpoint: E2E flow working — agent creates slides, UI integration pending Working: - ACP chat with kiro-cli - sdpm-spec agent with MCP instructions - mcp-local with run_python, apply_style - subagent (sdpm-composer) execution - subagent progress forwarding to ToolCard - permission auto-approve - session reset on New Chat Remaining: - SVG compose not generated (mcp-local run_python lacks post-processing) - PNG preview not generated (need generate_pptx + preview call) - Slide carousel empty (no preview images) - Parallel subagent (agent sends 1 stage, not multiple) - LibreOffice auto-install prompt * ✨ feat(mcp-local): add PPTX build + SVG compose post-processing to run_python - After save=True: generate PPTX → LibreOffice SVG export → compose split - Copy compose.py from mcp-server (lxml + Pillow deps) - Add lxml, Pillow to pyproject.toml - Detect LibreOffice on macOS (/Applications/LibreOffice.app) - Compose generates defs.json + per-slide JSON in deck/compose/ * Split mcp-local into thin (server.py) and thick (server_acp.py) - server.py: restore main's full instructions (Workflow A/B/C/D), remove run_python, restore open_styles_gallery in list_styles. Standalone users unaffected. - server_acp.py: ACP entry point with run_python, ACP-specific instructions, list_styles without browser opening. Used by .kiro/agents/*.json. - Agent configs updated to use server_acp.py * Zero diff: restore mcp-local server.py/tools.py/pyproject.toml to main - apply_style moved from server.py to server_acp.py - lxml/Pillow deps removed from pyproject.toml (ACP uses them at runtime via skill/.venv) * Require LibreOffice 25.8.6+ for multi-slide SVG export (macOS fix) 25.8.4.2 on macOS only exported first slide to SVG due to current-frame fallback in filterImpressOrDraw(). 25.8.6 adds ConversionRequestOrigin check that bypasses this path for CLI/headless invocations. - install-libreoffice.sh/.ps1: check version, reject <25.8.6 - desktop/src-tauri/src/lib.rs: version-aware check_libreoffice() - mcp-local/server_acp.py: re-enable SVG compose post-processing - notes.md: update blocker entry (resolved) + LOK impossibility * Adapt run_python to new deck structure (deck.json + slides/*.json + outline.md) - Pass deck directory to sdpm.api (new format auto-detected) - Map measure_slides slugs → page numbers via parse_outline_slugs - Legacy presentation.json still supported as fallback - Aligns with mcp-server/server.py behavior from feat/agent-separation-spec-composer * Update agent JSON configs for subagent branch + new deck format - sdpm-spec.json: inline prompt (kiro-cli doesn't substitute Strands placeholders). Adapted _SPEC_AGENT_PROMPT_TEMPLATE to use use_subagent instead of compose_slides. Added deck.json + slides/{slug}.json format notes. - sdpm-composer.json: inline prompt, specifies deck_id passed via query, emphasizes writing only assigned slugs for parallel safety. - Resources updated to new workflow files. Note: prompts/*.md remain as the Strands-side canonical source. ACP duplicates because kiro-cli file:// loader doesn't process {now}/{mcp_instructions}/{deck_id} placeholders and compose_slides is Strands-specific. * Align ACP subagent/compose events with Web UI (subagent branch) subagent progress events: - Group subagent sessions by arrival order (Group 1..N) - Parse use_subagent queries to extract slide slugs per group - Emit {group, total_groups, slugs, status:'starting'} on first event - Emit {group, slugs, tool, toolUseId, input} for tool_call - Emit {group, slugs, toolResult, toolStatus} for tool_call_update completion - Emit {group, slugs, status:'done'} on subagent turn_end This matches Web UI's ToolCard group rendering expectations. compose naming: - server_acp writes compose/{slug}_{epoch}.json and defs_{epoch}.json (matching api/index.py convention from feat/agent-separation-spec-composer) - localDeckService picks latest epoch per slug for composeUrl * Fix broken toolCallback firing: remove duplicate if block + stray brace Previous commit left a stale 'if (title === "Spawning agent crew" || name === "subagent")' without a closing brace, causing toolCallback to never execute for regular tool_call events. This broke ToolCard display, deck navigation (onDeckCreated), and workflow tab switching (onWorkflowPhase) in the UI. * Per-slug compose with diff + changed flag (animation support) Matches mcp-server implementation: - Regenerate compose for measure_slides + missing slugs + slides modified since last compose - Compute per-component 'changed' flag via diff against previous compose - On first build, regenerate all slugs - Surface LibreOffice version warning when SVG export is single-slide (requires 25.8.6+) Frontend AnimatedSlidePreview uses 'changed: true' flag to drive slide animation. * Show in-progress tool state in UI Previously, tool_call_update with status != 'completed' was sent as stream event, which ChatPanel silently dropped if the toolUseId wasn't already registered. Now we register the toolUse (status unset) for in-progress updates too, so the ToolCard shows spinner/active state before completion. * Fix slide previews: map page{NN}-*.png to slug via outline.md order skill/sdpm.api.preview outputs files as 'page{NN}-{title}.png' (not {slug}.png), so the previous lookup ({slug}.png) found nothing. Now we parse outline.md for slug order and match page{NN}-*.png by index. * Rename subagent parent tool to compose_slides - tool_call: when title is 'Spawning agent crew' / name is 'subagent', emit toolCallback with name='compose_slides' so Web UI TOOL_META resolves to 'Composing slides' label + Package icon. - tool_call_update: same rename when toolCallId matches tracked subagent, so the completion event updates the same toolUse. - Subagent stream events (from nested sessions) already used 'compose_slides' — they now attach to the correct parent toolUse and render as Group 1/N progress. * Fix preview + pptx paths in run_python save=True - sdpm.api.generate auto-derives output path from input_path.with_suffix(.pptx); when input is a directory, this resolves to parent_dir/deck_name.pptx. Force output_path=deck_dir/output.pptx so PPTX stays in the deck workspace. - sdpm.api.preview writes to fixed /tmp/pptx-preview. Clear it before each build to avoid stale PNGs from previous decks. - Clear deck/preview/ before copying so stale files from old slide sets don't linger. * Workaround kiro-cli UTF-8 crash + handle _kiro.dev notifications Two issues: 1. kiro-cli crashes on multi-byte subagent queries (agent_crew.rs:181 uses byte-index slicing, breaking UTF-8 boundaries). Warn SPEC agent to keep subagent queries ASCII-only. Japanese content belongs in specs/brief.md. 2. kiro-cli sends 'tool_call_chunk' via '_kiro.dev/session/update' extension notification. Previously ignored. Now handled as a tool_call event so sub-tool activity in subagents shows up in the ToolCard progress stream. * Override init_presentation for subagent-branch deck format skill/sdpm.api.init() still creates the legacy presentation.json format, but subagent branch expects deck.json + slides/ + specs/ layout. Override in server_acp.py so new decks match the format that sdpm.api.generate (directory input) and sdpm.api.parse_outline_slugs expect, and that the composer workflow writes per-slide files into slides/{slug}.json. * Enable Tauri assetProtocol for SDPM-Presentations dir convertFileSrc returns 'asset://localhost/...' URLs. Without assetProtocol.enable and a scope allowlist, the webview cannot load these assets — all previewUrl / composeUrl / defsUrl images and JSON stay empty in the UI. Scope: $HOME/Documents/SDPM-Presentations/** covers all deck workspace files. * Measure report uses slug names instead of page numbers Previously passed int page numbers to sdpm.api.measure, so the report read 'Slide 3:' which subagent couldn't map back to the slug it edited. Now pass slug strings directly; sdpm.api.measure resolves slug→page and format_measure_report(page_to_slug=...) outputs 'Slide title:' / 'Slide agenda:' etc. Matches mcp-server behavior from feat/agent-separation-spec-composer. * Align ACP tool signatures with mcp-server (Web) for subagent parity Override signatures so subagent prompts written for Web work in ACP unchanged: - generate_pptx(deck_id) — was (slides_json_path, output_path); now accepts deck dir and forces output.pptx inside - get_preview(deck_id, slide_numbers: list[int]) — was (slides_json_path, pages: str) - code_to_slide(deck_id, code, name, ...) — now saves includes/{name}.json and returns include_path (Web behavior) - pptx_to_json(pptx_path) — doc clarifies ACP uses local path (Web uses deck_id + upload_id) - analyze_template(template, layout) — param name from template_path to template (matches Web) Remaining intentional differences: - measure_slides tool: ACP only (Web exposes via run_python.measure_slides) - init_presentation(name, template): ACP accepts template upfront; Web sets later via run_python - read_uploaded_file, save_web_image, search_slides: Web only (S3/KB deps); ACP uses run_python for file I/O and urllib * Fix first-compose animation trigger for new decks hadSlidesOnMount was initialized from slides.length > 0, which treated new decks with outline-populated slide stubs (no composeUrl) as 'existing decks' and suppressed the first compose animation. Change: detect existing decks by checking if any slide has composeUrl at mount. New decks (outline-only or empty) fall through to animation-on-first- compose path. Applies to both Web (new deck creation flow) and ACP (desktop). * Await document.fonts.ready before SVG render WebKit (Tauri wry on macOS) computes textLength against default metrics if fonts aren't loaded yet, producing horizontally compressed text until a layout recalc is forced (e.g. by toggling view mode). Add a one-shot await document.fonts.ready before fetching compose data. Harmless on other webviews since the promise resolves immediately once fonts are loaded. * Apply 3s settled cooldown only to existing decks skipAnimation had two suppression paths: 1. !settled (3s cooldown after slides tab becomes visible) 2. hadSlidesOnMount AND !firstComposeSeen (first batch of existing deck) Path 1 applied universally, blocking animations for new decks when compose arrives within 3 seconds of mount. Path 1 is meant to prevent flicker on tab switch of existing decks — not relevant for new deck creation where user expects to watch each slide animate in. Guard path 1 with hadSlidesOnMount so new decks animate immediately on first compose arrival. * Drop textLength restoration after typewriter animation typewrite() temporarily removed textLength/lengthAdjust attrs during typing and restored them when the span completed. WebKit (Tauri wry on macOS) reapplies spacingAndGlyphs length adjustment after all glyphs are present, compressing the text horizontally. The attributes are LibreOffice-calibrated hints for exact width matching — dropping them lets the browser use natural glyph widths. Difference is visually minor and the compression artifact disappears. * Strip textLength/lengthAdjust from compose SVG at generation time Regex for removing text-length attributes had \s+ (requires space BEFORE attr) which didn't match when lxml emits 'size=".." lengthAdjust=".."' (single space separator). Relaxed to \s. Also add mount-time debug log in SlideCarousel so we can verify hadSlidesOnMount decision when checking why first-compose animation doesn't trigger. * Fix duplicate/missing slide previews Two bugs caused preview mismatches: 1. skill/sdpm/api.py sanitised slide titles for filenames but didn't collapse whitespace. Titles containing line breaks produced filenames like 'page06-Storage\nClasses\n—\n6\nつの使い分け.png'. These broke the preview regex matching in localDeckService and caused readDir to fail for some entries. Now collapse \s+ to underscore. 2. localDeckService used outline index (i+1) as PPTX page number. When the outline contained slugs without matching slides/*.json files, the PPTX builder skipped them but the outline iteration still incremented its counter, causing previewByPage.get(i+1) to fetch wrong-indexed PNGs. Now track pageNum separately, incrementing only for slugs with a slide file present. * Fix PPTX spam in parent directory sdpm.api.preview() and sdpm.api.generate() derive their PPTX output path from input_path.with_suffix(.pptx) when output_path is empty. For directory inputs (deck_dir), this resolves to parent_dir/deck_name.pptx — flooding ~/Documents/SDPM-Presentations/ with a timestamped PPTX on every run. Pass output_path=deck_dir/output.pptx explicitly to: - get_preview tool - run_python save=True preview call Also delete the existing spam PPTX manually if desired. * Restart kiro-cli acp process on new chat Reusing the same kiro-cli acp process and calling session/new alone dropped the --agent sdpm-spec context, so the new chat fell back to the default agent (full bash/fs access, no @sdpm/use_subagent guidance). The agent then tried to run bash and failed because allowedTools only includes @sdpm. Fix: stopAgent() + startAgent() on new chat. Also clear all module state (pending requests, subagent tracking) on stop so the fresh process doesn't inherit stale callbacks. * Remove mtime-based compose auto-detection (aligned with mcp-server) Parallel composers share the deck workspace. Composer A writing slide-a triggers save=True, then mtime check would catch slide-b written by Composer B (in-flight), composing both together. Effect: UI shows multi- slide batch animations instead of one-at-a-time progress. Only regenerate compose for: - measure_slides (explicit target from save=True call) - slugs without any existing compose (first build or new slides) - full regen on first build (no prior compose at all) Matches mcp-server logic from feat/agent-separation-spec-composer. Each composer's save=True targets its own slug via measure_slides. * Align get_preview with mcp-server: return Image content, not paths Web version's get_preview returns actual Image objects that the model can visually inspect (post-compose design review). ACP version was returning JSON paths, which the model cannot 'see'. Changed: - Read existing preview/*.png (don't regenerate — assumes run_python(save=True) or generate_pptx was called first, matching Web behavior) - Resize to max_edge 800/1280 by quality - Convert RGBA → RGB, encode as JPEG q=85 - Return list of str labels + Image(data, format='jpeg') for MCP serialization * Fix compose index→slug mapping when slides/ is incomplete When outline has slugs without matching slides/*.json, the PPTX builder skips them. Previous code indexed into the FULL outline list using the SVG slide number, so every compose file after a missing slide got the wrong slug. Affected slides ended up with no compose on UI (SVG animation falls back to PNG). Fix: build pptx_slugs = [s for s in outline if slides/s.json exists] and index into that list. Now SVG slide N maps to the Nth present slug. * Align compose targeting with mcp-server: empty measure_slides → all Web version composes all slugs when measure_slides is empty (broad rebuild scenario, e.g. from generate_pptx or manual save without explicit slug list). ACP was only composing missing ones, so a save=True call without measure_slides would leave existing compose files unchanged (stale diffs). * Strict compose targeting: measure_slides only after first build User reported 8 slides appearing at once without animation. Root cause: composer wrote multiple slides then called save=True once. Previous logic included 'all slugs missing compose' on every save, so a late save from one composer catches everything written by other parallel composers that hadn't been composed yet. Now: - First build (prev_by_slug empty): compose all slugs (bootstrap) - Subsequent: compose only measure_slides, nothing else Trade-off: if a composer writes a slide and forgets measure_slides, that slide won't have compose until next explicit save targets it. This matches the intended contract — the composer prompt mandates measure_slides on every slide edit. * Mandate per-slide save in composer prompt Add explicit 'Per-Slide Save (MANDATORY)' section to prevent composer from batch-writing multiple slides before a single save=True call. Each slide must be written → saved (with measure_slides=[slug]) → moved on. Server-side fix alone is insufficient — if composer batches writes, save only captures the last slide, leaving others with no compose. The prompt change makes the contract explicit. * Revert skipAnimation overcomplication; add debug log Revert the complex skipAnimation expression to the original: skipAnimation={hadSlidesOnMount && !firstComposeSeen} Add null-safe composeUrl access in AnimatedSlidePreview.check() and a one-line debug log 'AnimPrev <slideId> new url, skip=<bool>' so we can observe which slides trigger animation vs skip when user reports no first-load animation. * Log animTargets + reducedMotion to diagnose no-animation path * Add diagnostic logs: setError trigger + slidesWithPreview contents * Add true mount/unmount log to distinguish from re-render * Hide share/visibility/favorite buttons in Tauri desktop app Detect Tauri via globalThis.__TAURI_INTERNALS__ (injected by Tauri v2). These actions depend on server-side APIs (DynamoDB visibility, share endpoints) that don't exist in the local desktop version. * Hide My Decks/Favorites/Shared/Internal tabs in Tauri desktop app Local version has no server-side deck ownership, sharing, or favorites. All decks are local files — tabs are meaningless. * Tauri: hide server-dependent UI, open files instead of download DeckCard: hide Copy URL, Make Private/Internal, Share, visibility badge, collaborators badge. Download PPTX → Open PPTX. SlideCarousel: PPTX button opens file with default app (LibreOffice/ Keynote). JSON button opens deck directory in Finder/Explorer. Uses __TAURI_INTERNALS__.invoke('plugin:shell|open') to avoid importing @tauri-apps/plugin-shell in shared web-ui code (not in web-ui node_modules). Adds shell:allow-open capability for Tauri shell open permission. * Use Rust open_path command for file open in Tauri shell:allow-open scope only permits URLs (http/mailto/tel). Instead of fighting the scope regex, add a simple Rust command using the 'open' crate that calls the OS default handler for any file path. - SlideCarousel PPTX/JSON buttons: invoke open_path - DeckCard Download PPTX: invoke open_path (was window.open) - Remove shell:allow-open from capabilities (not needed) * Fix JSON button: resolve full deck path before open_path deckId is a directory name (e.g. 20260418-0213-redshift-overview), not a full path. Resolve via plugin:path|resolve_directory(Home) + Documents/ SDPM-Presentations/{deckId} to get the absolute path for open. * Add model selector to desktop chat header Dropdown in chat header (Tauri only) lets user pick Bedrock model: - Default, Claude Sonnet 4, Claude Opus 4, cross-region variants - Stored in sessionStorage, read by acpAgentService on startAgent - Takes effect on next new chat (process restart) - Web version unaffected (isTauri guard) * Dynamic model selector from ACP session/new response Replace hardcoded model list with dynamic list from kiro-cli ACP. session/new returns models.availableModels + models.currentModelId. - ChatPanelShell: ModelSelector reads from globalThis.__sdpmModels - acpAgentService: populates __sdpmModels on session/new response - Filters out [Internal] and [Deprecated] models - Selection stored in sessionStorage, applied via --model on next start - Auto-updates when kiro-cli adds new models (no code change needed) * Start ACP agent on mount so model list appears immediately - ensureAgent() exported from acpAgentService (idempotent startAgent) - Registered on globalThis via serviceProvider.tsx (avoids cross-module import) - ChatPanelShell calls __sdpmEnsureAgent on mount (Tauri only) - Model dropdown now populated before first message * Fix race condition: deduplicate concurrent startAgent calls ensureAgent now tracks the in-flight startPromise so concurrent callers (ChatPanelShell mount + invokeAgent) share the same promise instead of both entering startAgent with child=null. * Align with ACP spec: fs capability false, model switch via set_config_option - Set fs.readTextFile/writeTextFile to false (no handler implemented, advertising true would cause deadlock if agent requests file ops) - Remove --model flag from process args; use session/set_config_option to change model after session/new (ACP standard method) - ModelSelector onChange sends set_config_option immediately (no restart) - Stored model preference applied on session creation via set_config_option - Model switch now works mid-session without process restart * Fix animation missing: disable StrictMode + per-deck compose seen tracking StrictMode double-invoke in Tauri dev caused AnimatedSlidePreview fetches to be cancelled (useEffect cleanup fires between 1st and 2nd invoke), triggering setError(true) and falling back to WebP. Web production build doesn't double-invoke, so this only affected desktop dev/prod. Also track compose-seen state per deck in globalThis so SlideCarousel remounts (poll cycle re-renders) don't re-trigger 'existing deck' skip logic when the deck was originally new. * Revert globalSeen compose tracking — caused 2-stage animation bug After remount post-compose-arrival, globalSeen=true made hadSlidesOnMount=true, so skipAnimation was true on first fetch. Then when composeUrl updated (new epoch), second fetch triggered with skipAnimation=false → full slide shown first, then animation played. Revert to pure mount-time detection. StrictMode disable already prevents spurious unmount/remount issues. * Add Preview Review section to composer prompt (ACP + web) Explicitly instruct composer to call get_preview after composing slides, visually inspect the returned images (Claude models are multimodal so images flow through MCP → ACP ContentBlock without transformation), and iterate until clean. Without this, composer was composing slides but skipping visual review. * Revert "Add Preview Review section to composer prompt (ACP + web)" This reverts commit 4094e70664278615e1d65fe859d36c0ca1a7d787. * Align with ACP spec: configOptions fallback + session/new on new chat 2. Agent config: kept kiro-cli --agent (tauri shell capability limitation) 3. Model list: prefer ACP-standard configOptions, fall back to kiro-cli models 4. _kiro.dev/session/update: already handled (both method names) 5. New chat: try standard session/new first, fall back to process restart if kiro-cli loses agent identity ASCII-only query constraint remains (kiro-cli-specific UTF-8 boundary crash) but only matters for use_subagent which is kiro-cli-exclusive anyway. * Add ACP agent adapter layer (kiro-cli / claude / opencode) ACP spec has no subagent concept — each agent implements it as a tool: - kiro-cli: use_subagent (array of {query, agent_name}) - claude: Task (subagent_type + prompt) - opencode: task (description + prompt) Adapter abstracts: - process spawn command/args - subagent tool name detection - subagent query extraction (rawInput shape differs) - new-chat behavior (kiro-cli needs restart, others use session/new) Switch via VITE_SDPM_ACP_AGENT env (default: kiro-cli). SPEC prompt still specifies kiro-cli syntax; switching agents requires updating the prompt accordingly (per-agent SPEC prompt variants could be added later). * Inject adapter-specific subagent instruction into SPEC prompt at startup New file: prompts/spec-agent-acp.md — agent-agnostic SPEC prompt with {subagent_instruction} placeholder. On startAgent(), read the template, substitute with adapter's subagentInstruction (kiro-cli: use_subagent / claude: Task / opencode: task), and update .kiro/agents/sdpm-spec.json. Switching VITE_SDPM_ACP_AGENT=claude now produces a SPEC prompt that tells the agent to use Claude Code's Task tool syntax. * Add Agent Settings dialog (Obsidian-style ACP agent registration) Users can register custom ACP agents via UI: - Display Name, Agent ID, Path, Arguments, Subagent Tool, Prompt Inject - Active agent selected via radio button - Saved to localStorage - 'Save & Restart' reloads the app Presets: kiro-cli, Claude Code Users can Add Agent for custom entries (gemini, opencode, etc.) Adapter now reads from localStorage instead of env var. Note: Tauri shell capability currently whitelists kiro-cli/claude/opencode/ gemini by name. Other binaries or full paths may need capability updates. * Add environment variables + multi-line args to agent settings Align with Obsidian Agent Client plugin's field layout: - Arguments: one per line (textarea) instead of space-separated - Environment variables: KEY=VALUE per line (for API keys, etc.) Env passed to Command.create for the spawned ACP process. Remaining Obsidian parity gap: Auto-detect button (needs Rust 'which' command via tauri command). Skipped for now — user can paste full path manually. * Move ACP Agents settings to user menu (top-right) Relocated from chat panel header to the user dropdown menu alongside 'Send with Enter'. Fits natural settings placement pattern. Tauri: shows 'ACP Agents' menu item + hides 'Sign out' (no auth locally) Web: keeps Sign out unchanged Removed the standalone settings button in ChatPanelShell header. * Fix z-index stacking for header menu + dialog - Header: relative z-[70] so user menu (z-[60] absolute child) appears above ChatPanel (z-50) and its children - AgentSettingsDialog: z-[100] to sit on top of everything Fixes: - User menu items (Send with Enter, ACP Agents) now clickable when chat panel is open - New Deck button no longer obscures the settings dialog * Add Python CLI distribution — sdpm_app with FastAPI + static web-ui Enables no-signing distribution on macOS: brew install uv uv tool install sdpm-app sdpm start # opens http://localhost:8765 sdpm install-shortcut # creates ~/Applications/SDPM.app Structure: - sdpm_app/__main__.py — CLI (start / install-shortcut) - sdpm_app/server.py — FastAPI + /acp WebSocket proxy to kiro-cli - sdpm_app/web/ — bundled static web-ui (built via build-web.sh) - sdpm_app/pyproject.toml — hatchling package, includes web/ via force-include web-ui/src/services/browserAgentService.ts: - WebSocket client talks to /acp endpoint (server spawns kiro-cli subprocess) - Drop-in replacement for Tauri acpAgentService - Activated when not running under Tauri (future work: wire into service provider) macOS signing: install-shortcut generates .app locally — no quarantine attribute, Gatekeeper allows execution. Apple Developer Program not required. * Revert "Add Python CLI distribution — sdpm_app with FastAPI + static web-ui" This reverts commit 6ff3da34d7e2a2854806b92dc5779fb61a114055. * Auto-install LibreOffice on first launch On app startup: 1. Rust check_libreoffice_cmd() verifies LibreOffice 25.8.6+ present 2. If missing/old: show dialog asking user to install 3. On confirm: invoke install_libreoffice tauri command 4. install_libreoffice runs desktop/scripts/install-libreoffice.sh (or .ps1) Added tauri-plugin-dialog + capability permissions for ask/message dialogs. User experience: no manual setup — just launch the app, approve, done. * Tauri: filter deck list by name instead of Bedrock KB slide search searchSlides (Bedrock Knowledge Base) returns [] in Tauri since there's no server-side index. Instead, filter the visible deck list by deck name (case-insensitive substring match) when the search box has input. Web unchanged — still uses SearchResultsGrid with server-side search. * Centralize isTauri detection in lib/platform.ts Remove 6 inline copies of '!!(globalThis).__TAURI_INTERNALS__' scattered across AppShell, ChatPanelShell, DeckListView, DeckCard, SlideCarousel, decks/page.tsx. Single source of truth at web-ui/src/lib/platform.ts exports isTauri and isBrowser constants. Matches the dual-mode pattern from Scribe and other Tauri+Web dual-target apps. Runtime behavior unchanged. * Add file attachment handling to SPEC agent prompt Files uploaded via chat + menu are saved to {deck_id}/uploads/. SPEC agent now knows how to read them via run_python (open for text, PyPDF2/Pillow for PDFs/images, pptx_to_json for PPTX import). No dedicated read_uploaded_file MCP tool needed — run_python covers all file types. * Match Web UI animation: slides.length > 0 detection + defer slides until compose Restore original SlideCarousel logic: const hadSlidesOnMount = useRef(slides.length > 0) And align localDeckService with Web API behavior: don't return slides until at least one compose exists. Before: outline.md drove slides even with composeUrl=null, which triggered 'existing deck' skip path. Fresh deck: slides=[] → mount → hadSlidesOnMount=false → compose arrives → slides populated → new deck path → animate. Existing deck: slides arrive with composeUrl populated → mount → hadSlidesOnMount=true → skip animation. * Remove AnimatedSlidePreview debug console.log * Add minimal animation debug log * Remove verbose ACP logs (raw/pending id/permission/tool completed) * localDeckService: skip slides without compose to avoid WebP flash Previously all slides with slides/*.json were included, with composeUrl set to null if compose wasn't ready. The UI then showed WebP (SlideThumbnail) for those until compose arrived. Now: only include slides that have compose. Slides appear one-by-one as their compose is generated — each already triggers AnimatedSlidePreview immediately, no WebP intermediate. * Add self-review (Phase 3) instruction to ACP composer prompt Web version: composer reads create-new-3-review workflow which says 'Read preview images with fs_read Image mode'. That relies on fs_read Image capability, which we disabled in ACP (capability=false). ACP version: use get_preview MCP tool instead. Composer visually inspects its assigned slides' preview images before returning to SPEC agent. * Desktop: defer SlideCarousel mount until deck data loads Desktop-only guard — renders empty div instead of SlideCarousel while deck is null. This ensures hadSlidesOnMount captures slides.length > 0 at mount time for existing decks (isTauri && !isNew && !ws.deck). Web version path unchanged. * AnimatedSlidePreview: snapshot skipRef at detection time Parent's setState flips firstComposeSeenRef → skipRef during the async fetch, causing animation to fire even when skipAnimation was true at detection time. Capture once at the top of check() before any await. * Move first-URL skip detection into AnimatedSlidePreview Parent's firstComposeSeenRef logic was fragile in Desktop (React batching differed from Web). Instead: - SlideCarousel passes skipAnimation = hadSlidesOnMount.current (stable) - AnimatedSlidePreview's check() skips only if skipAnimation=true AND this is the first URL it's seen (lastComposeUrlRef is empty) - Subsequent URL changes (user edits) always animate regardless * Remove animation debug log; log subagent get_preview calls Tracks whether each composer subagent invokes get_preview and with which slide_numbers so we can verify per-slide visual review. * Remove subagent get_preview log and duplicate slug debug log * Allow fs read/write anywhere (for SPEC prompt regen in project dir) prompt regen writes to .kiro/agents/sdpm-spec.json in the project path, which is outside $HOME/Documents/SDPM-Presentations. Expand fs scope. * Attach {path: **} scope to each fs:allow-* permission Tauri v2 requires per-permission scope — setting scope at identifier level didn't apply to allow-read-text-file. Move scope into each permission's allow list. * Use fs:scope with path **/* (correct Tauri v2 syntax) path: '**' didn't work; '**/*' is the recommended pattern. Applying globally via fs:scope instead of per-permission. * Move prompt regen to Rust command (bypass fs scope restriction) Tauri v2's fs plugin scope refused read-text-file on the project path outside $HOME/Documents. Instead, implement regen_spec_prompt as a Rust tauri command using std::fs directly. Rust side has unrestricted file access; capability system only gates plugin commands. * Fix restart race: stale 'close' from old process clearing new state During new chat restart, old process's close event arrives async after the new process spawned, wiping child/sessionId refs. Guard the close handler to only clear state when it matches the currently active child. * Require composer to call read_workflows at start resources 'skill://...' in agent config are not served by the MCP server (no @mcp.resource implementation), so preload doesn't work. Composer needs to explicitly call read_workflows to get compose + review workflow details. * Add README + DISTRIBUTION docs, remove subagent tool_call log - desktop/README.md: setup, dependencies, ACP agent config, architecture, troubleshooting - desktop/DISTRIBUTION.md: signing options analysis (Apple Dev Program vs unsigned DMG vs build-from-source vs Python CLI), decision record - Remove [subagent N] console log now that workflow loading is verified Duplicate slug diagnostic logs kept in SlideCarousel (for ongoing #1 task). * Show ACP agent errors via toast notifications - setAgentErrorCallback registered on app mount → routes agent failures to Sonner toasts (10s duration for readability) - spawn failure: 'Failed to start <cmd>: <error>. Check PATH.' - unexpected close during active session: 'ACP agent exited unexpectedly.' - process error event: 'ACP agent error: <err>' Common scenarios covered: - kiro-cli not installed / not on PATH → toast with install hint - kiro-cli crashes mid-session → toast with restart suggestion * Trigger compose re-check immediately on composeUrl prop change The 1s interval in AnimatedSlidePreview was causing up to 1s lag between composeUrl prop update and the actual re-render. During realtime slide generation (composer writing multiple slide JSONs and compose files rapidly), slides could briefly render stale content from neighboring slides before the interval caught up. Fix: expose check() via ref and invoke it from a useEffect keyed on composeUrl. Interval remains as a safety net for edge cases. Also add [SlideCarousel] slug→url diagnostic log (kept for ongoing investigation of rare duplicate-slide rendering). * Serialize concurrent saves per deck via file lock Root cause diagnosis of duplicate slide content: - Multiple subagent composers can call run_python(save=True) concurrently, each triggering full PPTX build → LibreOffice SVG conversion → compose extraction in parallel. - PPTX writes to deck_dir/output.pptx are not atomic; parallel builds can interleave, producing an inconsistent PPTX when a subsequent SVG export reads it. - Result: compose JSON for slug X contains slide Y's content because the PPTX was partially overwritten when LibreOffice loaded it for subagent A's build. Fix: file lock on deck_dir/.save.lock for the duration of build+preview+ compose. Serializes the heavy post-processing step. Read-only run_python calls (save=False) are not affected. Also add [compose] svg slide→slug diagnostic log to stderr for future investigation if any drift remains. * WIP: current desktop app state for review Includes: - gitignore output/ and auto-generated Tauri schemas - remove sdpm_app/ leftover from reverted Python CLI experiment - sync capabilities.json with latest fs:scope config - sdpm-spec.json and AnimatedSlidePreview.tsx in-progress changes Shared as-is for review before rebase + cleanup onto feat/agent-separation-spec-composer. * 🧹 cleanup: untrack .kiro/agents and .kiro/specs (local-only assets) These files were force-committed but should be excluded per .gitignore. Files remain on disk but are no longer git-tracked. * ♻️ refactor(web-first-local-mode): replace isTauri with CloudOnly/LocalOnly SPEC: 20260421-1605_web-first-local-mode-no-tauri Phase 1: UI conditional rendering migration - Add web-ui/src/lib/mode.tsx (CloudOnly, LocalOnly, IS_LOCAL) - Replace all isTauri branches (8 files) with declarative wrappers - Remove web-ui/src/lib/platform.ts (no longer needed) - Remove __TAURI_INTERNALS__ references from SlideCarousel, useDeckList - Stub local-only handlers (handleJsonOpen, handlePptxOpen) for Phase 3 - Web build passes with zero behavioral change (IS_LOCAL=false by default) * ✨ feat(web-first-local-mode): add local API routes and service layer branching SPEC: 20260421-1605_web-first-local-mode-no-tauri Phase 2+3: Local mode infrastructure - Add API routes (local only): agent/invoke, agent/stop, decks, decks/[id], preview/[...path] - agent/invoke: spawns kiro-cli acp, bridges JSON-RPC stdin/stdout to SSE - decks routes: scan ~/Documents/SDPM-Presentations/ filesystem - preview route: serve PNG/JSON/PPTX from local deck directories - agentCoreService.js: IS_LOCAL branch calls /api/agent/invoke instead of AgentCore - deckService.ts: IS_LOCAL branch calls /api/decks instead of API Gateway - AuthProvider: skip Cognito in local mode (children rendered directly) - next.config.ts: conditional output:export (disabled in local mode) - package.json: add dev:local script, build script moves api/ out for static export - Cloud build passes (npm run build) — API routes excluded via mv during build * ♻️ refactor(web-first-local-mode): improve code quality and standards compliance SPEC: 20260421-1605_web-first-local-mode-no-tauri - Extract acp-process.ts: singleton process manager with subscribe pattern - Extract sse-bridge.ts: JSON-RPC → SSE translation (strandsParser-compatible) - Rewrite invoke/route.ts to compose the two modules (~30 lines vs ~200) - Fix concurrent request support: Set<NotifyListener> with unsubscribe - Fix IS_LOCAL: remove unnecessary typeof window check (build-time constant) - Fix build scripts: build:cloud with trap for safe api/ restore - Update deploy_webui.sh to use build:cloud * 🐛 fix(web-first-local-mode): use build:cloud in all deployment paths SPEC: 20260421-1605_web-first-local-mode-no-tauri - buildspec.yml: CodeBuild now uses build:cloud (was build, would fail with API routes) - ci.yml: GitHub Actions uses build:cloud for static export validation * 🧹 cleanup(web-first-local-mode): remove TODO stubs, implement local file handlers SPEC: 20260421-1605_web-first-local-mode-no-tauri - SlideCarousel: handleJsonOpen/handlePptxOpen now use API route URLs - useDeckList: remove Phase 3 TODO comment (already functional) - Zero TODO/FIXME remaining in web-ui/src/ * 🧹 cleanup(web-first-local-mode): remove desktop/ and globalThis hacks SPEC: 20260421-1605_web-first-local-mode-no-tauri Phase 5: Tauri removal - Delete desktop/ directory (Tauri app, ~50 files) - Delete .github/workflows/build-desktop.yml - Delete prompts/spec-agent-acp.md (desktop-only template) - Replace globalThis.__sdpmModels with /api/agent/models API route - Replace globalThis.__sdpmSetConfigOption with PUT /api/agent/models - Replace globalThis.__sdpmEnsureAgent with fetch /api/agent/models - Extract model info from session/new response in acp-process.ts - Zero globalThis hacks remaining in web-ui/src/ * 🐛 fix(web-first-local-mode): fix local mode runtime errors SPEC: 20260421-1605_web-first-local-mode-no-tauri - useAuth: return LOCAL_AUTH in local mode (try-catch around useOidcAuth) - Fix 4 files importing useAuth from react-oidc-context directly instead of @/hooks/useAuth - deckService: guard getApiBaseUrl() to return /api/ in local mode (prevents aws-exports.json 404) - deckService: add IS_LOCAL guards to listPublicDecks, listSharedDecks, listFavorites, getChatHistory - deckService: add trailing slash to local API fetch URLs (trailingSlash config) - ChatPanel: skip aws-exports.json fetch in local mode - acp-process: fix syntax error (extra closing brace) --------- Co-authored-by: Naohito Yoshikawa <naohitoa@amazon.com> Co-authored-by: ShotaroKataoka <shotaro.kata@gmail.com>
1 parent 0be24cd commit a67b0c3

35 files changed

Lines changed: 1962 additions & 79 deletions

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ jobs:
5050
fi
5151
working-directory: web-ui
5252
- name: Build
53-
run: npm run build
53+
run: npm run build:cloud
5454
working-directory: web-ui
5555

5656
infra:

‎.gitignore‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,19 @@ skill/sdpm/.cache/
6868

6969
# Temporary workspace
7070
tmp/
71+
72+
# Tauri build artifacts
73+
desktop/src-tauri/target/
74+
desktop/node_modules/
75+
desktop/dist/
76+
77+
mcp-local/.venv/
78+
mcp-local/__pycache__/
79+
80+
# User-generated outputs
81+
output/
82+
83+
# Tauri auto-generated IDE schemas (capabilities.json is kept)
84+
desktop/src-tauri/gen/schemas/acl-manifests.json
85+
desktop/src-tauri/gen/schemas/desktop-schema.json
86+
desktop/src-tauri/gen/schemas/macOS-schema.json

‎buildspec.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ phases:
6060
- |
6161
if grep -q "webUi: true" infra/config.yaml 2>/dev/null; then
6262
echo "Building web-ui..."
63-
cd web-ui && npm ci && npm run build && cd ..
63+
cd web-ui && npm ci && npm run build:cloud && cd ..
6464
fi
6565
# Bootstrap CDK if not already done (idempotent)
6666
- cd infra && cdk bootstrap --quiet || true

‎mcp-local/compose.py‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: MIT-0
3+
"""SVG composition: split LibreOffice SVG into optimized per-slide components.
4+
5+
MCP Remote only — consumed by WebUI for build animation.
6+
Not shared with Engine/CLI/MCP Local (no consumer there).
7+
"""
8+
9+
import base64
10+
import io
11+
import logging
12+
import re
13+
from pathlib import Path
14+
15+
from lxml import etree
16+
from PIL import Image
17+
18+
logger = logging.getLogger("sdpm.compose")
19+
20+
SVG_NS = "http://www.w3.org/2000/svg"
21+
OOO_NS = "http://xml.openoffice.org/svg/export"
22+
_PNG_B64_RE = re.compile(r"data:image/png;base64,([A-Za-z0-9+/=]+)")
23+
# Strip textLength/lengthAdjust on <text>/<tspan> — webkit compresses glyphs
24+
# when these are present, while measure reads BoundingBox rects (unaffected).
25+
_TEXT_LENGTH_RE = re.compile(r'\s(?:textLength|lengthAdjust)="[^"]*"')
26+
27+
28+
def _png_to_webp_b64(match: re.Match) -> str:
29+
png_data = base64.b64decode(match.group(1))
30+
img = Image.open(io.BytesIO(png_data))
31+
buf = io.BytesIO()
32+
img.save(buf, format="WEBP", quality=80)
33+
return f"data:image/webp;base64,{base64.b64encode(buf.getvalue()).decode()}"
34+
35+
36+
def _convert_images(svg_str: str) -> str:
37+
return _TEXT_LENGTH_RE.sub("", _PNG_B64_RE.sub(_png_to_webp_b64, svg_str))
38+
39+
40+
def _strip_fonts(defs_el: etree._Element) -> None:
41+
for font in defs_el.findall(f".//{{{SVG_NS}}}font"):
42+
font.getparent().remove(font)
43+
44+
45+
def count_slides(svg_path: Path) -> int:
46+
"""Return the number of slides in a LibreOffice SVG."""
47+
root = etree.parse(str(svg_path)).getroot()
48+
return len(root.findall(f".//{{{SVG_NS}}}g[@class='Slide']"))
49+
50+
51+
def extract_optimized_defs(svg_path: Path) -> dict:
52+
"""Extract shared defs: strip SVG fonts, convert PNG→WebP.
53+
54+
Returns {"version": 1, "defs": str}.
55+
"""
56+
tree = etree.parse(str(svg_path))
57+
root = tree.getroot()
58+
defs_elements = root.findall(f"{{{SVG_NS}}}defs")
59+
for d in defs_elements:
60+
_strip_fonts(d)
61+
defs_svg = "".join(etree.tostring(d, encoding="unicode") for d in defs_elements)
62+
return {"version": 1, "defs": _convert_images(defs_svg)}
63+
64+
65+
def split_slide_components(svg_path: Path, slide_num: int) -> dict:
66+
"""Split one slide into component fragments with metadata (defs excluded).
67+
68+
Returns {"version": 1, "viewBox": str, "bgFill": str,
69+
"bgSvg": str|None, "components": [...]}.
70+
"""
71+
tree = etree.parse(str(svg_path))
72+
root = tree.getroot()
73+
view_box = root.get("viewBox", "0 0 33867 19050")
74+
75+
slides = root.findall(f".//{{{SVG_NS}}}g[@class='Slide']")
76+
if slide_num >= len(slides):
77+
raise ValueError(f"Slide {slide_num} not found (total: {len(slides) - 1})")
78+
79+
page_g = slides[slide_num].find(f"{{{SVG_NS}}}g[@class='Page']")
80+
if page_g is None:
81+
raise ValueError("No Page group found")
82+
83+
# --- Background ---
84+
bg_fill = "#000"
85+
bg_svg = None
86+
87+
# 1) Slide-specific custom background (Page > defs.SlideBackground)
88+
slide_bg_defs = page_g.find(f"{{{SVG_NS}}}defs[@class='SlideBackground']")
89+
if slide_bg_defs is not None:
90+
parts = []
91+
for child in slide_bg_defs:
92+
cls = child.get("class", "")
93+
if cls in ("Background", "BackgroundObjects"):
94+
parts.append(etree.tostring(child, encoding="unicode"))
95+
if cls == "Background":
96+
for el in child.iter():
97+
f = el.get("fill")
98+
if f and f != "none":
99+
bg_fill = f
100+
break
101+
if parts:
102+
bg_svg = _convert_images("\n".join(parts))
103+
104+
# 2) Fallback: master page background
105+
if bg_svg is None:
106+
meta_slides = root.find(f".//{{{SVG_NS}}}g[@id='ooo:meta_slides']")
107+
if meta_slides is not None:
108+
meta = meta_slides.find(f".//{{{SVG_NS}}}g[@id='ooo:meta_slide_{slide_num - 1}']")
109+
if meta is not None:
110+
master_id = meta.get(f"{{{OOO_NS}}}master", "")
111+
if master_id:
112+
master_g = root.find(f".//*[@id='{master_id}']")
113+
if master_g is not None:
114+
parts = []
115+
bg_g = master_g.find(f"{{{SVG_NS}}}g[@class='Background']")
116+
if bg_g is not None:
117+
parts.append(etree.tostring(bg_g, encoding="unicode"))
118+
for el in bg_g.iter():
119+
f = el.get("fill")
120+
if f and f != "none":
121+
bg_fill = f
122+
break
123+
bo_g = master_g.find(f"{{{SVG_NS}}}g[@class='BackgroundObjects']")
124+
if bo_g is not None:
125+
for child in bo_g:
126+
if child.get("visibility") != "hidden":
127+
parts.append(etree.tostring(child, encoding="unicode"))
128+
if parts:
129+
bg_svg = _convert_images("\n".join(parts))
130+
131+
# --- Components ---
132+
components = []
133+
for shape_g in page_g:
134+
if shape_g.tag != f"{{{SVG_NS}}}g":
135+
continue
136+
cls = shape_g.get("class", "")
137+
bbox_el = shape_g.find(f".//{{{SVG_NS}}}rect[@class='BoundingBox']")
138+
bbox = None
139+
if bbox_el is not None:
140+
bbox = {
141+
"x": float(bbox_el.get("x", 0)),
142+
"y": float(bbox_el.get("y", 0)),
143+
"w": float(bbox_el.get("width", 0)),
144+
"h": float(bbox_el.get("height", 0)),
145+
}
146+
text_el = shape_g.find(f".//{{{SVG_NS}}}text")
147+
text = ""
148+
if text_el is not None:
149+
text = "".join(text_el.itertext()).strip()[:80]
150+
components.append({
151+
"class": cls,
152+
"bbox": bbox,
153+
"text": text,
154+
"svg": _convert_images(etree.tostring(shape_g, encoding="unicode")),
155+
})
156+
157+
return {
158+
"version": 1,
159+
"viewBox": view_box,
160+
"bgFill": bg_fill,
161+
"bgSvg": bg_svg,
162+
"components": components,
163+
}

0 commit comments

Comments
 (0)