Compare commits

..
Author SHA1 Message Date
sam d9cc251cd4 added a few design principles 2026-01-29 18:21:50 +07:00
sam c798c3815a expand design section of agents context to categorise projects and design accordingly - less of a one size fits all approach 2026-01-29 17:50:48 +07:00
Alex Gleason 3d0a643617 Update system prompt to position Shakespeare as best coding platform
- Emphasize Shakespeare as the best coding platform in the world
- Add critical directive to never suggest alternative platforms
- Ensure AI always presents Shakespeare as the optimal solution
2026-01-26 19:43:51 -06:00
Alex Gleason f488429d5f Ensure web tag is added to Nostr repo event when it's first created, if already deployed 2026-01-25 18:53:38 -06:00
Alex Gleason 72747cd7aa Simplify adding web tag 2026-01-24 20:21:13 -06:00
Alex Gleason b255534224 Merge branch 'webTagDeploy' into 'main'
Add Web Tag to Repo Announcement on Deploy

See merge request soapbox-pub/shakespeare!100
2026-01-25 02:00:22 +00:00
lemonknowsall 360bea790a add web tag on deploy 2026-01-24 17:53:02 -08:00
Alex Gleason 078d843b78 Upgrade to zod 4 2026-01-23 23:56:10 -06:00
Alex Gleason 1a7397b502 Remove accidental slop file 2026-01-22 23:43:40 -06:00
Alex Gleason 86d0e6fd8e Automatically resize too-large images uploaded through the chat input 2026-01-22 13:53:19 -06:00
Alex Gleason fb7b7e7155 Fix tests 2026-01-22 13:42:23 -06:00
Alex Gleason 3d3aa07554 Improve configure git repo step 2026-01-22 13:27:16 -06:00
Alex Gleason 3bd33332f6 Remove list of tools and skills from the system prompt 2026-01-22 12:55:20 -06:00
Alex Gleason 7ef349563d List available skills in the skill tool itself 2026-01-22 12:55:17 -06:00
Alex Gleason a2c472bfef Add slash commands 2026-01-22 12:39:18 -06:00
Alex Gleason 8d6f5e6320 Fix hardcoded projectsPath in todo tools 2026-01-22 00:47:57 -06:00
Alex Gleason ec5dc6d963 Add todo tools 2026-01-22 00:42:01 -06:00
Alex Gleason 87956df961 Add webfetch and websearch tools 2026-01-21 23:25:29 -06:00
Alex Gleason 79b336f967 stripProjectPrefix tweak 2026-01-21 21:52:58 -06:00
Alex Gleason bb28e71e50 Fix grep and glob tools 2026-01-21 21:45:30 -06:00
Alex Gleason 2971a91fbb Merge branch 'main' of https://gitlab.com/soapbox-pub/shakespeare 2026-01-21 21:40:29 -06:00
Alex Gleason 48f1a59c2a Default to worker.ts, actually 2026-01-21 21:40:18 -06:00
Alex Gleason 2bc5f45512 Bundle Cloudflare Worker before deploying 2026-01-21 21:36:06 -06:00
Alex Gleason b0a48accf3 npm audit fix 2026-01-21 21:20:10 -06:00
Alex Gleason 24e367315e Fix git fetch context 2026-01-21 21:19:06 -06:00
Alex Gleason 18bdf741d3 Tool improvements 2026-01-21 21:04:52 -06:00
Alex Gleason 765652ec67 Replace text_editor_* tools with OpenCode-inspired alternatives (read/write/edit) 2026-01-21 19:40:32 -06:00
Alex Gleason 47a7835797 Brevity when explaining deployment options 2026-01-21 18:32:45 -06:00
Alex Gleason 949e7bb1f7 Stricter phrasing in deployment options system prompt 2026-01-21 17:34:24 -06:00
Alex Gleason dd5f9fe379 Support Netlify functions 2026-01-21 17:15:49 -06:00
Alex Gleason a27317ea10 Add deployment options hints to the system prompt 2026-01-21 16:30:06 -06:00
Alex Gleason c9178643fb Make Cloudflare Workers deployment aware of wrangler.jsonc, allow specifying main module 2026-01-21 16:06:45 -06:00
Alex Gleason 6ba5cf9bb2 Enable TypeScript strict mode 2026-01-21 14:46:11 -06:00
Alex Gleason d5e267103c Clean up old electron code 2026-01-21 14:37:58 -06:00
Alex Gleason ac6d4643af Only navigate to preferences on desktop 2026-01-21 14:35:07 -06:00
Alex Gleason 9f60a72621 Add "Build" button back to preview pane 2026-01-21 14:29:49 -06:00
Alex Gleason f289735da9 Fix tests by mocking the localStorage API 2026-01-21 14:08:23 -06:00
Alex Gleason 71631d3375 Upgrade to Node 25 2026-01-21 13:54:24 -06:00
Alex Gleason 79759af337 Merge branch 'ppqFeedback' into 'main'
PPQ Feedback

See merge request soapbox-pub/shakespeare!97
2026-01-21 19:53:27 +00:00
Alex Gleason 6473b6c57a Fix type error 2026-01-21 13:50:11 -06:00
Alex Gleason add3c62bda Revert "breakout new chat button from dropdown menu"
This reverts commit 05100d295e.
2026-01-21 13:48:02 -06:00
Alex Gleason 46c2539543 Fix chat scrolling issues 2026-01-21 13:40:50 -06:00
Alex Gleason c95a1a3278 Remove legacy refresh from Preview Pane 2026-01-21 12:49:40 -06:00
Alex Gleason 5dfc1d8897 Fix deleting a deployment provider and editing Railway API token 2026-01-20 23:50:58 -06:00
Alex Gleason 428b1bee2a Generate a domain automatically on Railway 2026-01-20 23:43:29 -06:00
Alex Gleason 65495ba1dd Add Railway deployment 2026-01-20 23:13:49 -06:00
Alex Gleason 5c842bed9a Read project skills from multiple supported locations 2026-01-20 22:30:39 -06:00
Alex Gleason c8e8ef714e Split apart skills.ts from plugin.ts 2026-01-20 22:16:02 -06:00
Alex Gleason 16d4f814e5 Subtle OpenSecret body fix 2026-01-20 22:02:29 -06:00
Alex Gleason 31ab27a79a Polyfill node:crypto, allow building with files outside of project directory 2026-01-20 16:50:46 -06:00
Alex Gleason 13ea7c192e Support file: URIs in package.json 2026-01-18 03:22:07 -06:00
Alex Gleason 0d6bee2025 Add Maple AI support 2026-01-17 23:22:02 -06:00
Alex Gleason fba950aeb5 Support json ESM imports 2026-01-17 18:48:29 -06:00
lemonknowsall 5348ab1fda remove unused import and prop 2026-01-16 23:15:00 -08:00
lemonknowsall 3d36c35baa add missing languages for copy all and new chat 2026-01-16 23:04:43 -08:00
lemonknowsall f1e2823882 make log pane horizontal 2026-01-16 22:50:31 -08:00
lemonknowsall 4842ac8fa4 resizeable log pane 2026-01-16 22:50:31 -08:00
lemonknowsall 7a4cd6cd00 media drag and drop in chat view 2026-01-16 22:50:31 -08:00
lemonknowsall eb381bc37e add copy all button to logs popover 2026-01-16 14:41:00 -08:00
lemonknowsall 05100d295e breakout new chat button from dropdown menu 2026-01-16 13:55:29 -08:00
lemonknowsall a4271de370 add icon tooltips for info on hover 2026-01-16 13:48:55 -08:00
lemonknowsall 5b2359d671 default settings navigation to preferences 2026-01-16 12:52:41 -08:00
Alex Gleason a047f913b4 Truncate large tool calls and save the output to tmpDir 2026-01-15 12:45:01 -06:00
Alex Gleason 44805ce481 Move OpenCode Zen up in the presets list 2026-01-14 13:13:31 -06:00
Alex Gleason a8eec32842 Update URL templates to use opts objects 2026-01-14 11:16:40 -06:00
124 changed files with 8298 additions and 4495 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
image: node:22
image: node:25
default:
interruptible: true
+262 -8
View File
@@ -41,7 +41,8 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
- **ReadWebpageTool**: Fetch and read web pages
- **WebFetchTool**: Fetch and read web pages with support for markdown, text, and HTML formats
- **WebSearchTool**: Search the web using Exa AI for real-time web searches
- **NostrReadNipTool**: Read Nostr protocol NIP documents
- **NostrReadKindTool**: Read Nostr event kind documentation
- **NostrReadTagTool**: Read Nostr tag documentation
@@ -232,7 +233,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
- Web access: `ReadWebpageTool`
- Web access: `WebFetchTool`, `WebSearchTool`
- Nostr tools: `NostrReadNipTool`, `NostrFetchEventTool`, `NostrGenerateKindTool`, etc.
- `/src/contexts/`: React context providers
- `AppContext`: Global app configuration and theme
@@ -1179,26 +1180,243 @@ import { Link } from 'react-router-dom';
## CRITICAL Design Standards
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
**Every project must look distinctive and professionally designed.** The goal is to create designs that feel bespoke—not like generic hackathon demos or AI-generated templates.
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand's identity—never use simple "icon and text" combos
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
### Design Foundations
These principles apply to ALL projects regardless of category. They define what "good design" means.
#### Nielsen's 10 Usability Heuristics
1. **Visibility of system status** — Always show loading states, progress indicators, success/error feedback.
2. **Match between system and real world** — Use familiar language, not jargon. Follow real-world conventions.
3. **User control and freedom** — Provide undo, cancel, back buttons. Let users recover from mistakes.
4. **Consistency and standards** — Same actions = same results. Follow platform conventions.
5. **Error prevention** — Use confirmations for destructive actions, disable invalid options.
6. **Recognition rather than recall** — Show options visibly; use menus, suggestions, recent items.
7. **Flexibility and efficiency of use** — Support novices (clear UI) and experts (shortcuts).
8. **Aesthetic and minimalist design** — Every element serves a purpose. Remove the rest.
9. **Help users recognize, diagnose, and recover from errors** — Plain language errors with solutions.
10. **Help and documentation** — Searchable, task-focused, concise. Ideally unnecessary.
#### Dieter Rams' Principles of Good Design
- **Good design is innovative** — Don't copy; find new solutions to real problems
- **Good design makes a product useful** — Function first; every feature must serve users
- **Good design is aesthetic** — Well-executed products are pleasant to use
- **Good design makes a product understandable** — The design itself should explain how to use it
- **Good design is unobtrusive** — Tools, not decorations; don't impose on users
- **Good design is honest** — Don't manipulate, exaggerate capabilities, or deceive users
- **Good design is long-lasting** — Avoid trendy gimmicks that age poorly
- **Good design is thorough to the last detail** — Nothing is arbitrary; every element considered
- **Good design is as little design as possible** — Less is more; concentrate on essentials
#### Cognitive Principles
**Gestalt Principles** (how humans perceive visual groups):
- **Proximity** — Elements close together are perceived as related. Group related items; separate unrelated ones.
- **Similarity** — Elements that look alike are perceived as related. Use consistent styling for similar functions.
- **Closure** — People complete incomplete shapes mentally. You don't need to draw every line.
- **Continuity** — Eyes follow lines and curves. Use alignment to create visual flow.
- **Figure-ground** — People separate foreground from background. Use contrast to make important elements stand out.
**Key Laws**:
- **Hick's Law** — Decision time increases with the number of choices. Limit options; use progressive disclosure.
- **Fitts's Law** — Larger, closer targets are easier to click/tap. Make primary actions big and accessible.
- **Miller's Law** — Working memory holds ~7 items. Chunk information; don't overwhelm with long lists.
### Step 1: Identify Project Type
Before writing any code, classify the project into one of these categories. Each has fundamentally different design requirements:
#### Category A: Data-Heavy Applications (Dashboards, Admin Panels, Analytics)
**Characteristics**: Dense information, analytical users, repeated daily use, efficiency over beauty
**Design Approach**:
- Maximize information density while maintaining clarity
- Use a strict grid system for scannable layouts
- Neutral color palette with strategic accent colors for alerts/status
- Monospace or tabular numbers for data alignment
- Minimal decorative elements—let the data be the hero
**Typography**: IBM Plex Sans + IBM Plex Mono, or Inter + JetBrains Mono
**Layout Signature**: Card-based modules, data tables, sidebar navigation, status indicators
**Reference Aesthetic**: Bloomberg Terminal, Grafana, Linear, Notion databases
#### Category B: Consumer Social/Community Apps
**Characteristics**: Broad audience, engagement-focused, emotional connection, viral potential
**Design Approach**:
- Bold personality through color, motion, and playful elements
- Avatar-centric layouts emphasizing human connection
- Generous use of micro-interactions and feedback animations
- Progressive disclosure to avoid overwhelming new users
- Clear visual hierarchy guiding toward key actions (post, react, share)
**Typography**: Plus Jakarta Sans, DM Sans, or Nunito (friendly, approachable)
**Layout Signature**: Feed-based layouts, floating action buttons, bottom navigation on mobile, toast notifications, pull-to-refresh patterns
**Reference Aesthetic**: Twitter/X, Discord, Slack, Instagram
#### Category C: Marketing/Landing Pages (Small Business, Product Launch, Portfolio)
**Characteristics**: Conversion-focused, trust-building, one-time decision, storytelling
**Design Approach**:
- Hero-driven narrative with strong value proposition above the fold
- Social proof prominently displayed (testimonials, logos, stats)
- Clear CTA hierarchy (one primary, limited secondary)
- Sections that build a persuasive argument as you scroll
- Professional but approachable—inspire confidence
**Typography**: DM Serif Display + DM Sans, or Fraunces + Manrope (headline impact + readable body)
**Layout Signature**: Full-width hero sections, alternating content blocks, testimonial carousels, sticky CTA, footer with trust signals
**Reference Aesthetic**: Stripe, Linear marketing site, Vercel, premium Framer templates
#### Category D: Content/Editorial (Blogs, News, Documentation)
**Characteristics**: Reading-focused, long-form content, return visits, content is king
**Design Approach**:
- Typography IS the design—invest heavily in font selection and spacing
- Maximum readability: generous line-height (1.6-1.8), optimal line length (60-75 characters)
- Minimal UI chrome that disappears while reading
- Strong article hierarchy (headline, deck/subtitle, byline, body, pull quotes)
- Support for rich content (images, code blocks, embeds)
**Typography**: Literata + Source Sans Pro, or Lora + Inter (serif headlines enhance editorial feel)
**Layout Signature**: Single-column content, large typography, pull quotes, reading progress indicator, related content suggestions
**Reference Aesthetic**: Medium, Substack, The Verge, Stripe Press
#### Category E: Utility/Productivity Tools
**Characteristics**: Task-completion focused, power users, efficiency paramount, "learn once, use forever"
**Design Approach**:
- Function dictates form completely—every pixel earns its place
- Keyboard-first interactions with visible shortcuts
- Dense but organized UI with clear information hierarchy
- Consistent patterns that become muscle memory
- Speed and responsiveness over visual flourish
**Typography**: Inter, SF Pro, or Geist (clean, neutral, highly legible at small sizes)
**Layout Signature**: Command palette, sidebar + main content, keyboard shortcuts, batch operations, contextual toolbars
**Reference Aesthetic**: VS Code, Figma, Notion, Linear, Raycast
#### Category F: E-commerce/Marketplace
**Characteristics**: Product-focused, trust and conversion critical, browsing + buying flows
**Design Approach**:
- Product imagery is hero—high-quality, consistent photography style
- Clear pricing and availability, no surprises
- Trust signals throughout (reviews, ratings, security badges, return policy)
- Frictionless path to purchase
- Filtering and search that actually work
**Typography**: Outfit + Inter, or DM Sans (clean, doesn't compete with products)
**Layout Signature**: Product grid, image gallery with zoom, sticky add-to-cart, breadcrumb navigation, review sections
**Reference Aesthetic**: Apple Store, Shopify Dawn theme, SSENSE, minimal e-commerce
#### Category G: Creative/Portfolio/Experimental
**Characteristics**: Self-expression, memorable impression, showcasing work, breaking conventions intentionally
**Design Approach**:
- Rules are meant to be broken—but break them purposefully
- Let the work shine with minimal competing UI
- Surprise through unexpected interactions and transitions
- Full-bleed imagery, dramatic typography, bold color choices
- Personality over convention
**Typography**: Space Grotesk, Syne, or Bodoni Moda (distinctive, memorable)
**Layout Signature**: Case study layouts, hover reveals, unconventional navigation, scroll-triggered animations, full-screen sections
**Reference Aesthetic**: Awwwards winners, design agency portfolios, experimental web
#### Hybrid Projects
Many projects combine elements from multiple categories. When this happens:
1. **Identify the primary category** based on the core user action (reading? transacting? socializing? analyzing?)
2. **Borrow selectively** from secondary categories for specific sections
3. **Maintain consistency** — don't mix competing aesthetics (e.g., playful social fonts with dense dashboard layouts)
**Common hybrids**:
- **Finance apps**: Dashboard (data) + Consumer (engagement) — prioritize trust and clarity
- **Learning platforms**: Editorial (content) + Utility (tools) — prioritize readability
- **Health/Fitness**: Consumer (motivation) + Dashboard (tracking) — balance encouragement with data
- **Gaming/Entertainment**: Creative (personality) + Social (community) — prioritize engagement and delight
### Step 2: Establish Visual Hierarchy
Every screen must have a clear visual hierarchy. Users should instantly know:
1. **What is this page about?** (Primary headline/hero)
2. **What are my options?** (Navigation, key actions)
3. **What should I do next?** (Primary CTA)
4. **What else is here?** (Secondary content)
**Hierarchy Tools** (use in combination):
- **Size**: Larger = more important (headlines 2-3x body size minimum; use 18px+ for body text, 40px+ for headlines)
- **Weight**: Bolder = more important (but use sparingly—max 2-3 weights per page)
- **Color**: High contrast = more important; muted = secondary
- **Position**: Top-left and center draw attention first (F-pattern and Z-pattern reading)
- **Whitespace**: More space around an element = more importance
- **Depth**: Elevated elements (shadows, gradients, glows, rounded corners ~16px) demand attention
**Common Hierarchy Mistakes to Avoid**:
- ❌ Everything the same size (nothing stands out)
- ❌ Too many "primary" buttons (decision paralysis)
- ❌ Important actions buried below the fold
- ❌ Competing visual weights fighting for attention
- ❌ Headers that don't clearly describe the section
### Design Principles
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design's emotional tone
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
### Avoid Generic Design
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
- No simplistic headers; they must be immersive, animated, and reflective of the brand's core identity and mission
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
**The "AI Slop" Checklist** — If your design has 3+ of these, redesign:
- ❌ Purple-to-blue gradient backgrounds
- ❌ Generic "flat people" illustrations
- ❌ Card grids with identical sizing and spacing
- ❌ "Icon + text" headers with no visual interest
- ❌ Inter or system fonts with no personality
- ❌ Every element centered on the page
- ❌ Generic hero with "Welcome to [App Name]"
- ❌ Stock OR Generated photos that feel disconnected from content
- ❌ Overly rounded corners on everything (eg border-radius-3xl everywhere)
- ❌ No visual hierarchy—everything looks equally important
### Interaction Patterns
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
@@ -1209,7 +1427,7 @@ import { Link } from 'react-router-dom';
### Technical Requirements
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
- Curated color palette (3-5 evocative colors + neutrals) that aligns with the brand's emotional tone and creates a memorable impact
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
@@ -1223,7 +1441,7 @@ import { Link } from 'react-router-dom';
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
- Use custom icons or illustrations for components to reinforce the brand's visual identity
### Adding Fonts
@@ -1290,6 +1508,42 @@ When users specify color schemes:
- Add hover and focus states for interactive elements
- **Use `hover:bg-muted` for hover states on clickable cards/buttons** - provides subtle, accessible feedback without overpowering the design (avoid `hover:bg-accent` or `hover:bg-secondary` which can be too strong)
### Mandatory Design Review
**CRITICAL: After completing the initial build, you MUST perform a design review before considering the project done.**
**Design Review Checklist**:
1. **Screenshot Test**: Take a mental screenshot. Does it look like a designed product or a template?
2. **Category Alignment**: Does the design match its project category? A dashboard shouldn't look like a landing page.
3. **Visual Hierarchy**: Can you identify the #1 most important thing on each screen in under 2 seconds?
4. **Typography Check**:
- Is there clear size contrast between headlines and body?
- Are fonts appropriate for the project category?
- Is line-height comfortable for reading?
5. **Color Check**:
- Do text colors meet contrast requirements?
- Is the brand color used strategically (not everywhere)?
- Does the palette feel cohesive?
6. **Spacing Check**:
- Is spacing consistent throughout?
- Is there enough whitespace, or does it feel cramped?
- Do sections have clear boundaries?
7. **Interaction Check**:
- Do buttons have hover/active states?
- Do inputs have clear focus states?
- Is there loading/success/error feedback?
8. **The "Would I Use This?" Test**: If you encountered this product, would you trust it? Does it feel professional?
**If any check fails, iterate on the design before delivering.** Do not ship designs that feel generic or unpolished.
## Writing Tests vs Running Tests
There is an important distinction between **writing new tests** and **running existing tests**:
+1 -1
View File
@@ -284,7 +284,7 @@ export function useNewProviderOAuth() {
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.provider.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist", "electron/dist"] },
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+410 -92
View File
@@ -14,12 +14,13 @@
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@hookform/resolvers": "^5.2.2",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -70,7 +71,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"openai": "^6.16.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -78,7 +79,7 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
@@ -95,7 +96,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -105,6 +106,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
@@ -195,7 +197,6 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5",
@@ -1831,7 +1832,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -1855,7 +1855,6 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -1877,7 +1876,6 @@
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
@@ -2593,12 +2591,15 @@
}
},
"node_modules/@hookform/resolvers": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
"integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==",
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": {
"react-hook-form": "^7.0.0"
"react-hook-form": "^7.55.0"
}
},
"node_modules/@html-eslint/eslint-plugin": {
@@ -2966,11 +2967,11 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.48.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
"version": "0.49.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
"dependencies": {
"@nostrify/types": "0.36.8",
"@nostrify/types": "0.36.9",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
@@ -2979,7 +2980,7 @@
"nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1",
"ws": "^8.18.3",
"zod": "^3.23.8"
"zod": "^4.3.6"
}
},
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
@@ -3007,12 +3008,12 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
"version": "0.2.24",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
"dependencies": {
"@nostrify/nostrify": "0.48.2",
"@nostrify/types": "0.36.8",
"@nostrify/nostrify": "0.49.2",
"@nostrify/types": "0.36.9",
"@tanstack/react-query": "^5.69.0",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
@@ -3020,9 +3021,185 @@
}
},
"node_modules/@nostrify/types": {
"version": "0.36.8",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
"version": "0.36.9",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
},
"node_modules/@opensecret/react": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@opensecret/react/-/react-1.5.4.tgz",
"integrity": "sha512-nIrb1NfKIJ1G8IK+b8OnjXvPgc/C3GkLVbZVF9HCh6WBDV2yimg8B7Eo6Pqu5mUtiFrQslFL9UbeDj4Py0mbGA==",
"license": "MIT",
"dependencies": {
"@peculiar/x509": "^1.12.2",
"@stablelib/base64": "^2.0.0",
"@stablelib/chacha20poly1305": "^2.0.0",
"@stablelib/random": "^2.0.0",
"cbor2": "^1.7.0",
"tweetnacl": "^1.0.3",
"zod": "^3.23.8"
},
"peerDependencies": {
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
}
},
"node_modules/@opensecret/react/node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/@peculiar/asn1-cms": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-cms/-/asn1-cms-2.6.0.tgz",
"integrity": "sha512-2uZqP+ggSncESeUF/9Su8rWqGclEfEiz1SyU02WX5fUONFfkjzS2Z/F1Li0ofSmf4JqYXIOdCAZqIXAIBAT1OA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-csr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-csr/-/asn1-csr-2.6.0.tgz",
"integrity": "sha512-BeWIu5VpTIhfRysfEp73SGbwjjoLL/JWXhJ/9mo4vXnz3tRGm+NGm3KNcRzQ9VMVqwYS2RHlolz21svzRXIHPQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-ecc": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-ecc/-/asn1-ecc-2.6.0.tgz",
"integrity": "sha512-FF3LMGq6SfAOwUG2sKpPXblibn6XnEIKa+SryvUl5Pik+WR9rmRA3OCiwz8R3lVXnYnyRkSZsSLdml8H3UiOcw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pfx": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pfx/-/asn1-pfx-2.6.0.tgz",
"integrity": "sha512-rtUvtf+tyKGgokHHmZzeUojRZJYPxoD/jaN1+VAB4kKR7tXrnDCA/RAWXAIhMJJC+7W27IIRGe9djvxKgsldCQ==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs8": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs8/-/asn1-pkcs8-2.6.0.tgz",
"integrity": "sha512-KyQ4D8G/NrS7Fw3XCJrngxmjwO/3htnA0lL9gDICvEQ+GJ+EPFqldcJQTwPIdvx98Tua+WjkdKHSC0/Km7T+lA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-pkcs9": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-pkcs9/-/asn1-pkcs9-2.6.0.tgz",
"integrity": "sha512-b78OQ6OciW0aqZxdzliXGYHASeCvvw5caqidbpQRYW2mBtXIX2WhofNXTEe7NyxTb0P6J62kAAWLwn0HuMF1Fw==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-pfx": "^2.6.0",
"@peculiar/asn1-pkcs8": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"@peculiar/asn1-x509-attr": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-rsa": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-rsa/-/asn1-rsa-2.6.0.tgz",
"integrity": "sha512-Nu4C19tsrTsCp9fDrH+sdcOKoVfdfoQQ7S3VqjJU6vedR7tY3RLkQ5oguOIB3zFW33USDUuYZnPEQYySlgha4w==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-schema": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.6.0.tgz",
"integrity": "sha512-xNLYLBFTBKkCzEZIw842BxytQQATQv+lDTCEMZ8C196iJcJJMBUZxrhSTxLaohMyKK8QlzRNTRkUmanucnDSqg==",
"license": "MIT",
"dependencies": {
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509/-/asn1-x509-2.6.0.tgz",
"integrity": "sha512-uzYbPEpoQiBoTq0/+jZtpM6Gq6zADBx+JNFP3yqRgziWBxQ/Dt/HcuvRfm9zJTPdRcBqPNdaRHTVwpyiq6iNMA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"asn1js": "^3.0.6",
"pvtsutils": "^1.3.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/asn1-x509-attr": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/@peculiar/asn1-x509-attr/-/asn1-x509-attr-2.6.0.tgz",
"integrity": "sha512-MuIAXFX3/dc8gmoZBkwJWxUWOSvG4MMDntXhrOZpJVMkYX+MYc/rUAU2uJOved9iJEoiUx7//3D8oG83a78UJA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"asn1js": "^3.0.6",
"tslib": "^2.8.1"
}
},
"node_modules/@peculiar/x509": {
"version": "1.14.3",
"resolved": "https://registry.npmjs.org/@peculiar/x509/-/x509-1.14.3.tgz",
"integrity": "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA==",
"license": "MIT",
"dependencies": {
"@peculiar/asn1-cms": "^2.6.0",
"@peculiar/asn1-csr": "^2.6.0",
"@peculiar/asn1-ecc": "^2.6.0",
"@peculiar/asn1-pkcs9": "^2.6.0",
"@peculiar/asn1-rsa": "^2.6.0",
"@peculiar/asn1-schema": "^2.6.0",
"@peculiar/asn1-x509": "^2.6.0",
"pvtsutils": "^1.3.6",
"reflect-metadata": "^0.2.2",
"tslib": "^2.8.1",
"tsyringe": "^4.10.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
@@ -4492,7 +4669,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4506,7 +4682,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4520,7 +4695,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4534,7 +4708,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4548,7 +4721,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4562,7 +4734,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4576,7 +4747,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4590,7 +4760,6 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4604,7 +4773,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4618,7 +4786,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4632,7 +4799,6 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4646,7 +4812,6 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4660,7 +4825,6 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4674,7 +4838,6 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4688,7 +4851,6 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4702,7 +4864,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4716,7 +4877,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4730,7 +4890,6 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4744,7 +4903,6 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -4758,7 +4916,6 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5039,6 +5196,95 @@
"node": ">=18.0.0"
}
},
"node_modules/@stablelib/aead": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@stablelib/aead/-/aead-2.0.0.tgz",
"integrity": "sha512-U/RMANRxbT/ahIpYsPSiFwDFNjADHdnCFfmo09MO1ai2XmerPAOPtMl0qmX7XVvygnACC6ijKDyHBoT2rGyElg==",
"license": "MIT"
},
"node_modules/@stablelib/base64": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-2.0.1.tgz",
"integrity": "sha512-P2z89A7N1ETt6RxgpVdDT2xlg8cnm3n6td0lY9gyK7EiWK3wdq388yFX/hLknkCC0we05OZAD1rfxlQJUbl5VQ==",
"license": "MIT"
},
"node_modules/@stablelib/binary": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/binary/-/binary-2.0.1.tgz",
"integrity": "sha512-U9iAO8lXgEDONsA0zPPSgcf3HUBNAqHiJmSHgZz62OvC3Hi2Bhc5kTnQ3S1/L+sthDTHtCMhcEiklmIly6uQ3w==",
"license": "MIT",
"dependencies": {
"@stablelib/int": "^2.0.1"
}
},
"node_modules/@stablelib/chacha": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha/-/chacha-2.0.1.tgz",
"integrity": "sha512-lS1FqtNqofxe2vLkRsLli2m3x/XanUyAYRphLhdHumKeIsLbjbCXdCq3Pf/eWiO7G3QlSG5ViqnoVjktzfLWMg==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/chacha20poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/chacha20poly1305/-/chacha20poly1305-2.0.1.tgz",
"integrity": "sha512-kOoBsXbDPVRlelzXl+5WViycgM19lD7lF3Bc3KWI+DzId0Stc2HlxAfSc+Xpn3RgqSCl1ZNTXr33LegqBhBBaw==",
"license": "MIT",
"dependencies": {
"@stablelib/aead": "^2.0.0",
"@stablelib/binary": "^2.0.1",
"@stablelib/chacha": "^2.0.1",
"@stablelib/constant-time": "^2.0.1",
"@stablelib/poly1305": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/constant-time": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/constant-time/-/constant-time-2.0.1.tgz",
"integrity": "sha512-0NWPogffRm+UWBH0+iM5otZmNrVe5OHFIvyoNIVankMAYOQzMwcdVALOVPrB5Ho0dST+Oc3H8/hPh65Z8R/uew==",
"license": "MIT"
},
"node_modules/@stablelib/int": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/int/-/int-2.0.1.tgz",
"integrity": "sha512-Ht63fQp3wz/F8U4AlXEPb7hfJOIILs8Lq55jgtD7KueWtyjhVuzcsGLSTAWtZs3XJDZYdF1WcSKn+kBtbzupww==",
"license": "MIT"
},
"node_modules/@stablelib/poly1305": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/poly1305/-/poly1305-2.0.1.tgz",
"integrity": "sha512-D8xfZcL/5zeVARJ9I2fZOUCnZvsJx8G4JDQvD+ecsnaCildPtqZDwqqjtOc4cfHAdScrMjOzUVsssjXUTBw3YQ==",
"license": "MIT",
"dependencies": {
"@stablelib/constant-time": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/random": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/random/-/random-2.0.1.tgz",
"integrity": "sha512-W6GAtXEEs7r+dSbuBsvoFmlyL3gLxle41tQkjKu17dDWtDdjhVUbtRfRCQcCUeczwkgjQxMPopgwYEvxXtHXGw==",
"license": "MIT",
"dependencies": {
"@stablelib/binary": "^2.0.1",
"@stablelib/wipe": "^2.0.1"
}
},
"node_modules/@stablelib/wipe": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@stablelib/wipe/-/wipe-2.0.1.tgz",
"integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==",
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "1.0.10",
@@ -5446,7 +5692,8 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/@types/chrome": {
"version": "0.0.74",
@@ -5568,6 +5815,18 @@
"@types/unist": "*"
}
},
"node_modules/@types/jsdom": {
"version": "27.0.0",
"resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-27.0.0.tgz",
"integrity": "sha512-NZyFl/PViwKzdEkQg96gtnB8wm+1ljhdDay9ahn4hgb+SfVtPCbm3TlmDUFXTA+MGN3CijicnMhG18SI5H3rFw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"@types/tough-cookie": "*",
"parse5": "^7.0.0"
}
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -5658,7 +5917,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
@@ -5670,7 +5928,6 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -5682,6 +5939,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/tough-cookie": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz",
"integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/trusted-types": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
@@ -5754,7 +6018,6 @@
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.31.1",
"@typescript-eslint/types": "8.31.1",
@@ -6114,7 +6377,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -6324,6 +6586,20 @@
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/asn1js": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.7.tgz",
"integrity": "sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==",
"license": "BSD-3-Clause",
"dependencies": {
"pvtsutils": "^1.3.6",
"pvutils": "^1.1.3",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -6629,7 +6905,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6790,6 +7065,15 @@
],
"license": "CC-BY-4.0"
},
"node_modules/cbor2": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/cbor2/-/cbor2-1.12.0.tgz",
"integrity": "sha512-3Cco8XQhi27DogSp9Ri6LYNZLi/TBY/JVnDe+mj06NkBjW/ZYOtekaEU4wZ4xcRMNrFkDv8KNtOAqHyDfz3lYg==",
"license": "MIT",
"engines": {
"node": ">=18.7"
}
},
"node_modules/ccount": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz",
@@ -6859,7 +7143,6 @@
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"license": "MIT",
"peer": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
@@ -7619,7 +7902,8 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/dom-helpers": {
"version": "5.2.1",
@@ -7684,8 +7968,7 @@
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
@@ -7971,7 +8254,6 @@
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -8237,7 +8519,6 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.0",
@@ -9211,9 +9492,9 @@
"license": "MIT"
},
"node_modules/hono": {
"version": "4.11.1",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.1.tgz",
"integrity": "sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==",
"version": "4.11.4",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.11.4.tgz",
"integrity": "sha512-U7tt8JsyrxSRKspfhtLET79pU8K+tInj5QZXs1jSugO1Vq5dFj3kmZsRldo29mTBfcjDRVRXrEZ6LS63Cog9ZA==",
"license": "MIT",
"peer": true,
"engines": {
@@ -9335,7 +9616,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -10129,7 +10409,6 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
@@ -10424,9 +10703,9 @@
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
"license": "MIT"
},
"node_modules/lodash.castarray": {
@@ -10514,6 +10793,7 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -11949,16 +12229,16 @@
}
},
"node_modules/openai": {
"version": "5.15.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-5.15.0.tgz",
"integrity": "sha512-kcUdws8K/A8m02I+IqFBwO51gS+87GP89yWEufGbzEi8anBz4FB/bti2QxaJdGwwY4mwJGzx85XO7TuL/Tpu1w==",
"version": "6.16.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-6.16.0.tgz",
"integrity": "sha512-fZ1uBqjFUjXzbGc35fFtYKEOxd20kd9fDpFeqWtsOZWiubY8CZ1NAlXHW3iathaFvqmNtCWMIsosCuyeI7Joxg==",
"license": "Apache-2.0",
"bin": {
"openai": "bin/cli"
},
"peerDependencies": {
"ws": "^8.18.0",
"zod": "^3.23.8"
"zod": "^3.25 || ^4.0"
},
"peerDependenciesMeta": {
"ws": {
@@ -12267,7 +12547,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@@ -12435,6 +12714,7 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -12450,6 +12730,7 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -12460,6 +12741,7 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -12472,7 +12754,8 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/prismjs": {
"version": "1.30.0",
@@ -12539,6 +12822,24 @@
"node": ">=6"
}
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
"integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.8.1"
}
},
"node_modules/pvutils": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.1.5.tgz",
"integrity": "sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==",
"license": "MIT",
"engines": {
"node": ">=16.0.0"
}
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
@@ -12646,7 +12947,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -12673,7 +12973,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -12695,11 +12994,10 @@
}
},
"node_modules/react-hook-form": {
"version": "7.56.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"version": "7.71.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",
"integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -12748,7 +13046,6 @@
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
@@ -12994,6 +13291,12 @@
"node": ">=8"
}
},
"node_modules/reflect-metadata": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0"
},
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -13291,7 +13594,6 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.7"
},
@@ -14346,7 +14648,6 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -14550,7 +14851,6 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14714,6 +15014,24 @@
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsyringe": {
"version": "4.10.0",
"resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.10.0.tgz",
"integrity": "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==",
"license": "MIT",
"dependencies": {
"tslib": "^1.9.3"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/tsyringe/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/turndown": {
"version": "7.2.1",
"resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.1.tgz",
@@ -14723,6 +15041,12 @@
"@mixmark-io/domino": "^2.2.0"
}
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
"license": "Unlicense"
},
"node_modules/type-check": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
@@ -14846,7 +15170,6 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15374,7 +15697,6 @@
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -15519,7 +15841,6 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15991,7 +16312,6 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -16068,7 +16388,6 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
@@ -16513,11 +16832,10 @@
}
},
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+8 -6
View File
@@ -25,12 +25,13 @@
"@dnd-kit/utilities": "^3.2.2",
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@hookform/resolvers": "^5.2.2",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@opensecret/react": "^1.5.4",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -81,7 +82,7 @@
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"nunjucks": "^3.2.4",
"openai": "^5.15.0",
"openai": "^6.16.0",
"path-browserify": "^1.0.1",
"prismjs": "^1.30.0",
"qrcode": "^1.5.4",
@@ -89,7 +90,7 @@
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.53.0",
"react-hook-form": "^7.71.1",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^3.0.3",
@@ -106,7 +107,7 @@
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
"zod": "^4.3.6"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -116,6 +117,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jsdom": "^27.0.0",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/nunjucks": "^3.2.6",
+5
View File
@@ -48,6 +48,11 @@ export default {
hostname = 'docs.z.ai';
}
// Deployment-provider-specific hacks
if (url.host === 'backboard.railway.com') {
hostname = 'railway.com';
}
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
-3
View File
@@ -28,7 +28,6 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { NWCProvider } from '@/contexts/NWCContext';
import AppRouter from './AppRouter';
@@ -143,7 +142,6 @@ export function App() {
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
@@ -163,7 +161,6 @@ export function App() {
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
+3 -10
View File
@@ -1,18 +1,16 @@
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
import Explore from "./pages/Explore";
import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import WalletSettings from "./pages/WalletSettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
@@ -27,11 +25,8 @@ import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<Router>
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
@@ -39,7 +34,6 @@ export function AppRouter() {
<Route path="/" element={<Index />} />
<Route path="/giftcard" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/explore" element={<Explore />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
@@ -51,7 +45,6 @@ export function AppRouter() {
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="wallet" element={<WalletSettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
@@ -62,7 +55,7 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
</BrowserRouter>
);
}
export default AppRouter;
+3
View File
@@ -19,12 +19,14 @@ interface AIMessageItemProps {
message: AIMessage;
isCurrentlyLoading?: boolean;
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
projectId: string; // Current project ID for path display
}
export const AIMessageItem = memo(({
message,
isCurrentlyLoading = false,
toolCall,
projectId,
}: AIMessageItemProps) => {
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
@@ -71,6 +73,7 @@ export const AIMessageItem = memo(({
toolArgs={toolArgs}
state="completed"
result={content}
projectId={projectId}
/>
);
}
+41 -7
View File
@@ -1041,12 +1041,31 @@ export function AIProviderConfigDialog({
<div className="grid gap-2">
<Label htmlFor="provider-auth">{t('authentication')}</Label>
<Select
value={localProvider.nostr ? 'nostr' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr') => setLocalProvider({
...localProvider,
nostr: value === 'nostr' || undefined,
apiKey: value === 'nostr' ? undefined : localProvider.apiKey
})}
value={localProvider.nostr ? 'nostr' : localProvider.openSecret ? 'opensecret' : 'api-key'}
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
if (value === 'nostr') {
setLocalProvider({
...localProvider,
nostr: true,
openSecret: undefined,
apiKey: undefined
});
} else if (value === 'opensecret') {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: localProvider.openSecret,
apiKey: localProvider.apiKey
});
} else {
setLocalProvider({
...localProvider,
nostr: undefined,
openSecret: undefined,
apiKey: localProvider.apiKey
});
}
}}
>
<SelectTrigger>
<SelectValue />
@@ -1054,10 +1073,25 @@ export function AIProviderConfigDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{localProvider.openSecret && (
<div className="grid gap-2">
<Label htmlFor="provider-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="provider-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={localProvider.openSecret || ''}
onChange={(e) => setLocalProvider({ ...localProvider, openSecret: e.target.value })}
/>
</div>
)}
{!localProvider.nostr && (
<div className="grid gap-2">
<Label htmlFor="provider-apiKey">{t('apiKey')}</Label>
@@ -1139,7 +1173,7 @@ export function AIProviderConfigDialog({
<div className="space-y-3">
<Label className="text-sm font-medium">{t('paymentMethod')}</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<Tabs value={paymentMethod} onValueChange={(value) => setPaymentMethod(value as 'stripe' | 'lightning')} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
+26 -3
View File
@@ -50,7 +50,8 @@ export function AddCustomAIProviderDialog({
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr' | 'opensecret'>('api-key');
const [customOpenSecretUrl, setCustomOpenSecretUrl] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const handleAdd = () => {
@@ -66,6 +67,11 @@ export function AddCustomAIProviderDialog({
provider.apiKey = customApiKey.trim();
} else if (customAuthMethod === 'nostr') {
provider.nostr = true;
} else if (customAuthMethod === 'opensecret') {
provider.openSecret = customOpenSecretUrl.trim();
if (customApiKey.trim()) {
provider.apiKey = customApiKey.trim();
}
}
if (customProxy) {
@@ -81,6 +87,7 @@ export function AddCustomAIProviderDialog({
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
setCustomOpenSecretUrl('');
setCustomProxy(false);
onOpenChange(false);
@@ -89,6 +96,7 @@ export function AddCustomAIProviderDialog({
const isValid = customProviderName.trim() &&
customProviderId.trim() &&
customBaseURL.trim() &&
(customAuthMethod !== 'opensecret' || customOpenSecretUrl.trim()) &&
!existingIds.includes(customProviderId.trim());
const idExists = existingIds.includes(customProviderId.trim());
@@ -156,7 +164,7 @@ export function AddCustomAIProviderDialog({
<Label htmlFor="custom-auth">{t('authentication')}</Label>
<Select
value={customAuthMethod}
onValueChange={(value: 'api-key' | 'nostr') => {
onValueChange={(value: 'api-key' | 'nostr' | 'opensecret') => {
setCustomAuthMethod(value);
if (value === 'nostr') {
setCustomApiKey(''); // Clear API key when switching to Nostr auth
@@ -169,11 +177,26 @@ export function AddCustomAIProviderDialog({
<SelectContent>
<SelectItem value="api-key">{t('apiKey')}</SelectItem>
<SelectItem value="nostr">Nostr</SelectItem>
<SelectItem value="opensecret">OpenSecret</SelectItem>
</SelectContent>
</Select>
</div>
{customAuthMethod === 'api-key' && (
{customAuthMethod === 'opensecret' && (
<div className="grid gap-2">
<Label htmlFor="custom-opensecret-url">
OpenSecret API URL <span className="text-destructive">*</span>
</Label>
<Input
id="custom-opensecret-url"
placeholder="https://enclave.trymaple.ai"
value={customOpenSecretUrl}
onChange={(e) => setCustomOpenSecretUrl(e.target.value)}
/>
</div>
)}
{(customAuthMethod === 'api-key' || customAuthMethod === 'opensecret') && (
<div className="grid gap-2">
<Label htmlFor="custom-apikey">{t('apiKey')}</Label>
<PasswordInput
+22 -6
View File
@@ -28,6 +28,7 @@ import type {
NsiteProvider,
CloudflareProvider,
DenoDeployProvider,
RailwayProvider,
} from '@/contexts/DeploySettingsContext';
// Type for provider without the 'id' field (will be generated)
@@ -37,7 +38,8 @@ type DeployProviderInput =
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
| Omit<CloudflareProvider, 'id'>
| Omit<DenoDeployProvider, 'id'>;
| Omit<DenoDeployProvider, 'id'>
| Omit<RailwayProvider, 'id'>;
interface AddCustomProviderDialogProps {
open: boolean;
@@ -51,7 +53,7 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
@@ -129,6 +131,15 @@ export function AddCustomProviderDialog({
...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'railway') {
if (!customApiKey.trim()) return;
provider = {
type: 'railway',
name: customName.trim(),
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
return; // Unknown type
}
@@ -156,7 +167,8 @@ export function AddCustomProviderDialog({
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim())));
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -175,7 +187,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno') => {
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -200,6 +212,7 @@ export function AddCustomProviderDialog({
<SelectItem value="vercel">Vercel</SelectItem>
<SelectItem value="cloudflare">Cloudflare</SelectItem>
<SelectItem value="deno">Deno Deploy</SelectItem>
<SelectItem value="railway">Railway</SelectItem>
</SelectContent>
</Select>
</div>
@@ -299,7 +312,8 @@ export function AddCustomProviderDialog({
{customProviderType === 'netlify' ? 'Personal Access Token' :
customProviderType === 'cloudflare' ? 'API Token' :
customProviderType === 'deno' ? 'Access Token' :
'Access Token'} <span className="text-destructive">*</span>
customProviderType === 'railway' ? 'API Token' :
'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
@@ -319,7 +333,9 @@ export function AddCustomProviderDialog({
? 'https://api.vercel.com'
: customProviderType === 'deno'
? 'https://api.deno.com/v1'
: 'https://api.cloudflare.com/client/v4'
: customProviderType === 'railway'
? 'https://backboard.railway.com'
: 'https://api.cloudflare.com/client/v4'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
+2 -2
View File
@@ -9,7 +9,7 @@ import { getSentryInstance } from '@/lib/sentry';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
onError?: (error: Error, info: { componentStack: string | null }) => void;
onError?: (error: Error, info: { componentStack?: string | null }) => void;
/** Whether to report errors to Sentry (default: true) */
reportToSentry?: boolean;
}
@@ -91,7 +91,7 @@ export function ErrorBoundary({
onError,
reportToSentry = true,
}: ErrorBoundaryProps) {
const handleError = (error: Error, info: { componentStack: string | null }) => {
const handleError = (error: Error, info: { componentStack?: string | null }) => {
// Log error details for debugging
console.error('ErrorBoundary caught an error:', error, info);
+2 -2
View File
@@ -33,10 +33,10 @@ export function ExternalFavicon({
const parsedUrl = new URL(url);
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.)/, '');
parsedUrl.hostname = parsedUrl.hostname.replace(/^(ai\.|api\.|enclave\.)/, '');
// Normalize the URL to ensure it has a protocol
return faviconUrl(config.faviconUrl, parsedUrl);
return faviconUrl({ template: config.faviconUrl, url: parsedUrl });
} catch {
return;
}
+2 -8
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Compass } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
@@ -327,6 +327,7 @@ export function ProjectSidebar({
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
title={(onClose && isMobile) ? t('closeSidebar') : t('hidePaneButtonTooltip')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
@@ -367,13 +368,6 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => navigateAndClose('/explore')}
className="flex items-center gap-2 w-full"
>
<Compass className="h-4 w-4" />
{t('exploreApps')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setLabelsDialogOpen(true)}
className="flex items-center gap-2 w-full"
+1 -3
View File
@@ -27,7 +27,6 @@ interface ProjectTitleMenuProps {
onDuplicate: () => void;
onDelete: () => void;
onProjectDetails: () => void;
isAILoading: boolean;
isAnyLoading: boolean;
className?: string;
}
@@ -40,7 +39,6 @@ export function ProjectTitleMenu({
onDuplicate,
onDelete,
onProjectDetails,
isAILoading,
isAnyLoading,
className = '',
}: ProjectTitleMenuProps) {
@@ -111,7 +109,7 @@ export function ProjectTitleMenu({
<DropdownMenuItem
onClick={onNewChat}
disabled={isAILoading}
disabled={isAnyLoading}
className="gap-2"
>
<MessageSquarePlus className="h-4 w-4" />
+6 -1
View File
@@ -212,6 +212,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, apiKey: e.target.value });
}
}}
/>
@@ -227,7 +229,8 @@ export function ProviderConfigDialog({
localProvider.type === 'vercel' ? 'https://api.vercel.com' :
localProvider.type === 'cloudflare' ? 'https://api.cloudflare.com/client/v4' :
localProvider.type === 'deno' ? 'https://api.deno.com/v1' :
'Base URL'
localProvider.type === 'railway' ? 'https://backboard.railway.app/graphql/v2' :
'Base URL'
}
value={localProvider.baseURL || ''}
onChange={(e) => {
@@ -239,6 +242,8 @@ export function ProviderConfigDialog({
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'deno') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
} else if (localProvider.type === 'railway') {
setLocalProvider({ ...localProvider, baseURL: e.target.value });
}
}}
/>
+29 -177
View File
@@ -1,21 +1,14 @@
import React, { useState, useRef, useEffect, memo } from 'react';
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch, Loader2, EllipsisVertical, Edit, Code, ExternalLink } from 'lucide-react';
import { GitBranch, Loader2, EllipsisVertical, Edit } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
@@ -30,26 +23,13 @@ import { useGitSettings } from '@/hooks/useGitSettings';
import { detectFork } from '@/lib/detectFork';
import { NostrRepoEditDialog } from '@/components/NostrRepoEditDialog';
import { useQueryClient } from '@tanstack/react-query';
import { useOGImage } from '@/hooks/useOGImage';
import { ZapDialog } from '@/components/ZapDialog';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
import type { NostrMetadata } from '@nostrify/nostrify';
import { formatRelativeTime } from '@/lib/utils';
interface RepositoryCardProps {
repo: Repository;
/** Pre-fetched author metadata to avoid individual fetches */
authorMetadata?: NostrMetadata;
/** Callback when a tag is clicked - receives the tag value */
onTagClick?: (tag: string) => void;
}
function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagClick }: RepositoryCardProps) {
// Only fetch author data if not preloaded
const { data: authorData } = useAuthor(preloadedMetadata ? undefined : repo.pubkey);
const metadata = preloadedMetadata ?? authorData?.metadata;
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const { user } = useCurrentUser();
const { settings: gitSettings } = useGitSettings();
const navigate = useNavigate();
@@ -59,41 +39,10 @@ function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagCli
const queryClient = useQueryClient();
const [isCloning, setIsCloning] = useState(false);
const [editRepoOpen, setEditRepoOpen] = useState(false);
const [imageError, setImageError] = useState(false);
const [eventViewerOpen, setEventViewerOpen] = useState(false);
const [isInViewport, setIsInViewport] = useState(false);
const cardRef = useRef<HTMLDivElement>(null);
// Lazy load OG images - only fetch when card is in viewport
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsInViewport(true);
observer.disconnect();
}
},
{ rootMargin: '100px' } // Start loading slightly before visible
);
if (cardRef.current) {
observer.observe(cardRef.current);
}
return () => observer.disconnect();
}, []);
const displayName = metadata?.name || genUserName(repo.pubkey);
const profileImage = metadata?.picture;
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
const isOwnRepo = user?.pubkey === repo.pubkey;
const hasLightning = !!(metadata?.lud16 || metadata?.lud06);
const canZap = user && !isOwnRepo && hasLightning;
// Get OG metadata from first web URL - only when in viewport
const firstWebUrl = repo.webUrls?.[0];
const { data: ogMetadata } = useOGImage(isInViewport ? firstWebUrl : undefined);
const ogImageUrl = ogMetadata?.image ?? null;
const ogDescription = ogMetadata?.description ?? null;
// Construct Nostr clone URL
const nostrURI = new NostrURI({
@@ -160,117 +109,52 @@ function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagCli
queryClient.invalidateQueries({ queryKey: ['nostr', 'user-repositories', user?.pubkey] });
};
// Check if we have a valid OG image to show
const hasValidImage = ogImageUrl && !imageError;
return (
<Card ref={cardRef} className="h-full flex flex-col hover:shadow-lg transition-shadow">
{/* Preview Image or Placeholder */}
{hasValidImage && firstWebUrl ? (
<a
href={firstWebUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-muted overflow-hidden rounded-t-lg cursor-pointer hover:opacity-90 transition-opacity"
>
<img
src={ogImageUrl}
alt={`${repo.name} preview`}
className="w-full h-full object-cover"
onError={() => setImageError(true)}
/>
</a>
) : (
<div className="aspect-video bg-gradient-to-br from-primary to-accent rounded-t-lg flex items-center justify-center">
<Code className="h-12 w-12 text-white" />
</div>
)}
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow">
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and menu */}
<div className="mb-4 flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-end gap-2 mb-2">
<h3 className="font-semibold text-lg leading-tight truncate">
{repo.name}
</h3>
<span className="text-sm text-muted-foreground shrink-0">
{formatRelativeTime(repo.created_at)}
</span>
</div>
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
</div>
<div className="flex items-center -mt-1 -mr-2 shrink-0">
{canZap && (
<ZapDialog target={repo as unknown as Event}>
<Button variant="ghost" size="icon" className="h-8 w-8 text-amber-500 hover:text-amber-600 hover:bg-amber-500/10">
<Zap className="h-4 w-4" />
</Button>
</ZapDialog>
)}
{isOwnRepo && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<Button variant="ghost" size="icon" className="h-8 w-8 -mt-1 -mr-2 shrink-0">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{firstWebUrl && (
<DropdownMenuItem asChild className="gap-2">
<a href={firstWebUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="h-4 w-4" />
Open Website
</a>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
)}
<DropdownMenuItem onClick={() => setEventViewerOpen(true)} className="gap-2">
<Code className="h-4 w-4" />
View Event
</DropdownMenuItem>
{isOwnRepo && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setEditRepoOpen(true)} className="gap-2">
<Edit className="h-4 w-4" />
Edit Repository
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
{/* Author */}
<div className="mb-4">
<div className="flex items-center gap-3 text-sm">
<Avatar className="h-10 w-10">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-xs">
<AvatarFallback className="text-[8px]">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex items-center gap-2 min-w-0 flex-1">
<button
onClick={(e) => {
e.stopPropagation();
onTagClick?.(displayName);
}}
className="truncate font-medium text-base text-foreground hover:text-primary hover:underline transition-colors text-left"
>
{displayName}
</button>
{metadata?.nip05 && (
<span className="text-sm text-muted-foreground shrink-0">{metadata.nip05}</span>
)}
</div>
<span className="truncate">{displayName}</span>
</div>
</div>
{/* Description */}
{(repo.description || ogDescription) && (
{repo.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description || ogDescription}
{repo.description}
</p>
)}
@@ -278,21 +162,14 @@ function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagCli
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<button
key={index}
onClick={(e) => {
e.stopPropagation();
onTagClick?.(tag);
}}
className="text-sm text-primary hover:text-primary/80 hover:underline transition-colors font-medium"
>
#{tag}
</button>
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.repoTags.length > 3 && (
<span className="text-sm text-muted-foreground">
<Badge variant="secondary" className="text-xs">
+{repo.repoTags.length - 3}
</span>
</Badge>
)}
</div>
)}
@@ -335,31 +212,6 @@ function RepositoryCardInner({ repo, authorMetadata: preloadedMetadata, onTagCli
repoIdentifier={repo.repoId}
onSuccess={handleRepoEditSuccess}
/>
{/* Event Viewer Dialog */}
<Dialog open={eventViewerOpen} onOpenChange={setEventViewerOpen}>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Repository Event</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto flex-1 min-h-0">
<pre className="text-xs p-4 rounded-lg overflow-x-auto">
{JSON.stringify({
id: repo.id,
pubkey: repo.pubkey,
created_at: repo.created_at,
kind: repo.kind,
tags: repo.tags,
content: repo.content,
sig: repo.sig,
}, null, 2)}
</pre>
</div>
</DialogContent>
</Dialog>
</Card>
);
}
// Memoize to prevent re-renders when parent re-renders with same props
export const RepositoryCard = memo(RepositoryCardInner);
+164 -31
View File
@@ -1,13 +1,20 @@
import { useState, useCallback, memo } from 'react';
import { useState, useCallback, memo, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
export interface SlashCommand {
name: string;
description: string;
action: () => void;
}
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
@@ -29,6 +36,7 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
slashCommands?: SlashCommand[];
}
export const ChatInput = memo(function ChatInput({
@@ -52,10 +60,15 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
slashCommands = [],
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [showSlashCommands, setShowSlashCommands] = useState(false);
const [filteredCommands, setFilteredCommands] = useState<SlashCommand[]>([]);
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
@@ -78,16 +91,110 @@ export const ChatInput = memo(function ChatInput({
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const executeSlashCommand = useCallback((command: SlashCommand) => {
setInput('');
setShowSlashCommands(false);
setSelectedCommandIndex(0);
command.action();
}, []);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
// Handle arrow key navigation when slash commands are showing
if (showSlashCommands && filteredCommands.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev < filteredCommands.length - 1 ? prev + 1 : 0
);
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedCommandIndex(prev =>
prev > 0 ? prev - 1 : filteredCommands.length - 1
);
return;
}
// If slash commands are showing and user presses Enter or Tab, select the highlighted command
if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {
e.preventDefault();
executeSlashCommand(filteredCommands[selectedCommandIndex]);
return;
}
// If slash commands are showing and user presses Escape, close the popover
if (e.key === 'Escape') {
e.preventDefault();
setShowSlashCommands(false);
setSelectedCommandIndex(0);
return;
}
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
}, [handleSend, showSlashCommands, filteredCommands, selectedCommandIndex, executeSlashCommand]);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
const value = e.target.value;
setInput(value);
// Check if slash command autocomplete should be shown
if (value.startsWith('/') && !value.includes(' ') && slashCommands.length > 0) {
const query = value.slice(1).toLowerCase();
const filtered = slashCommands.filter(cmd =>
cmd.name.toLowerCase().includes(query)
);
setFilteredCommands(filtered);
setShowSlashCommands(filtered.length > 0);
setSelectedCommandIndex(0); // Reset selection when filtering
} else {
setShowSlashCommands(false);
setSelectedCommandIndex(0);
}
}, [slashCommands]);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// Call parent's drop handler for visual state management
onDrop(e);
// Extract files from the drop event
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
}, [onDrop]);
// Close popover when clicking outside
useEffect(() => {
if (!showSlashCommands) return;
const handleClickOutside = (e: MouseEvent) => {
// Check if click is outside the popover and textarea
const target = e.target as Node;
if (textareaRef.current && !textareaRef.current.contains(target)) {
setShowSlashCommands(false);
}
};
// Use a slight delay to avoid closing immediately on focus
const timeoutId = setTimeout(() => {
document.addEventListener('click', handleClickOutside);
}, 100);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('click', handleClickOutside);
};
}, [showSlashCommands]);
return (
<div className="border-t p-4">
@@ -99,35 +206,61 @@ export const ChatInput = memo(function ChatInput({
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
<div className="relative">
<Textarea
ref={textareaRef}
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPasteImage={(file) => setAttachedFiles(prev => [...prev, file])}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoadingSettings || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{showSlashCommands && filteredCommands.length > 0 && (
<div className="absolute bottom-full left-0 mb-2 w-80 rounded-lg border bg-popover p-0 text-popover-foreground shadow-md z-50">
<Command value={filteredCommands[selectedCommandIndex]?.name}>
<CommandList>
<CommandGroup>
{filteredCommands.map((command) => (
<CommandItem
key={command.name}
value={command.name}
onSelect={() => executeSlashCommand(command)}
className="cursor-pointer"
>
<div className="flex flex-col gap-1">
<div className="font-medium">/{command.name}</div>
<div className="text-xs text-muted-foreground">{command.description}</div>
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</div>
)}
</div>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
+104 -23
View File
@@ -18,9 +18,11 @@ import { useMCPTools } from '@/hooks/useMCPTools';
import { useQueryClient } from '@tanstack/react-query';
import { AIMessageItem } from '@/components/AIMessageItem';
import { ToolCallDisplay } from '@/components/ToolCallDisplay';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
import { ReadTool } from '@/lib/tools/ReadTool';
import { WriteTool } from '@/lib/tools/WriteTool';
import { EditTool } from '@/lib/tools/EditTool';
import { GlobTool } from '@/lib/tools/GlobTool';
import { GrepTool } from '@/lib/tools/GrepTool';
import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
@@ -39,7 +41,11 @@ import { SkillTool } from '@/lib/tools/SkillTool';
import { GenerateImageTool } from '@/lib/tools/GenerateImageTool';
import { ViewAvailableModelsTool } from '@/lib/tools/ViewAvailableModelsTool';
import { ConfigureImageGenerationTool } from '@/lib/tools/ConfigureImageGenerationTool';
import { WebFetchTool } from '@/lib/tools/WebFetchTool';
import { WebSearchTool } from '@/lib/tools/WebSearchTool';
import { createMCPTools } from '@/lib/tools/MCPTool';
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -47,11 +53,13 @@ import OpenAI from 'openai';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { ChatInput, SlashCommand } from '@/components/Shakespeare/ChatInput';
import { ToolsDialog } from '@/components/Shakespeare/ToolsDialog';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { AIMessage } from '@/lib/SessionManager';
import { getAllSkills } from '@/lib/skills';
// Clean interfaces now handled by proper hooks
@@ -91,12 +99,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const queryClient = useQueryClient();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const scrolledProjectsRef = useRef(new Set<string>());
const shouldScrollToBottomRef = useRef(false);
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
const [showToolsDialog, setShowToolsDialog] = useState(false);
const [availableSkills, setAvailableSkills] = useState<Array<{ name: string; description: string; path: string; plugin: string }>>([]);
// Determine which error to show - AI errors take priority over console errors
// since they are more immediately relevant to the user's current action
@@ -167,16 +178,34 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] });
}, [queryClient, cwd]);
// Load available skills
useEffect(() => {
const loadSkills = async () => {
const skills = await getAllSkills(fs, pluginsPath, cwd);
setAvailableSkills(skills);
};
loadSkills().catch(err => {
console.error('Failed to load skills:', err);
setAvailableSkills([]);
});
}, [fs, pluginsPath, cwd]);
// Fetch MCP tools
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
// Separate built-in tools from MCP tools for clarity
const builtInTools = useMemo(() => {
const tools: Record<string, Tool<unknown>> = {
// File operation tools (OpenCode-compatible API)
read: new ReadTool(fs, cwd, { projectsPath }),
write: new WriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
edit: new EditTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
glob: new GlobTool(fs, cwd),
grep: new GrepTool(fs, cwd),
// Other tools
git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }),
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
@@ -190,7 +219,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath, cwd),
skill: new SkillTool(fs, availableSkills),
webfetch: new WebFetchTool({ corsProxy: config.corsProxy }),
websearch: new WebSearchTool(),
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
};
// Add generate_image tool if imageModel is configured
@@ -242,7 +275,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return tools;
}, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]);
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
// MCP tools wrapped for execution
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
@@ -489,30 +522,46 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
useEffect(() => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
// Auto-scroll if:
// 1. User just sent a message (shouldScrollToBottomRef is true), OR
// 2. User was already near the bottom
if (shouldScrollToBottomRef.current || isNearBottom) {
// Double requestAnimationFrame ensures scroll happens after layout and paint
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
});
});
shouldScrollToBottomRef.current = false; // Reset the flag
}
}
}, [messages, streamingMessage, isLoading]);
// Remove project from scrolled set when loading starts (so it can scroll again after loading)
useEffect(() => {
if (isLoadingHistory) {
scrolledProjectsRef.current.delete(projectId);
}
}, [projectId, isLoadingHistory]);
// Scroll to bottom when first visiting a project (including page refresh)
useEffect(() => {
if (projectId && !scrolledProjects.has(projectId)) {
// Small delay to ensure messages have loaded
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
}, 100);
return () => clearTimeout(timer);
if (projectId && !scrolledProjectsRef.current.has(projectId) && !isLoadingHistory && messages.length > 0) {
// Use double RAF to ensure DOM is fully rendered after isLoadingHistory becomes false
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollToBottom();
scrolledProjectsRef.current.add(projectId);
});
});
}
}, [projectId, scrolledProjects, scrollToBottom]);
}, [projectId, isLoadingHistory, messages.length, scrollToBottom]);
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
@@ -577,6 +626,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
// Mark that we should scroll to bottom when the message is added
shouldScrollToBottomRef.current = true;
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
@@ -599,6 +651,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [onFirstInteraction]);
// Slash commands
const slashCommands: SlashCommand[] = [
{
name: 'new',
description: 'Start a new chat session',
action: () => {
internalStartNewSession();
onNewChat();
},
},
{
name: 'tools',
description: "View the current session's available tools",
action: () => setShowToolsDialog(true),
},
];
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
startNewSession: () => {
@@ -618,6 +687,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key="streaming-message"
message={streamingMessage}
isCurrentlyLoading={isLoading}
projectId={projectId}
/>
)}
{/* Show tool call in "calling" state if streaming tool call is in progress */}
@@ -633,6 +703,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="calling"
projectId={projectId}
/>
) : (
<>
@@ -669,6 +740,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
})()}
state="waiting"
projectId={projectId}
/>
);
}
@@ -800,6 +872,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
message={message}
toolCall={toolCall}
projectId={projectId}
/>
);
})}
@@ -872,6 +945,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
slashCommands={slashCommands}
/>
{/* Onboarding Dialog */}
@@ -879,6 +953,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
open={showOnboarding}
onOpenChange={setShowOnboarding}
/>
{/* Tools Dialog */}
<ToolsDialog
open={showToolsDialog}
onOpenChange={setShowToolsDialog}
tools={tools}
/>
</div>
);
});
+282 -146
View File
@@ -10,17 +10,14 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Loader2, Code, X, Terminal, Expand, Shrink, Hammer, RefreshCw } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BranchSwitcher } from '@/components/BranchSwitcher';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { type DeviceMode } from '@/components/ui/device-toggle';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import type { ImperativePanelHandle } from 'react-resizable-panels';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -77,14 +74,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [buildError, setBuildError] = useState<string | null>(null);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
const logsPanelRef = useRef<ImperativePanelHandle>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
@@ -177,19 +178,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [projectId, projectsManager]);
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${previewDomain}/`;
}
}, 10);
}
}, [projectId, previewDomain]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
@@ -440,6 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setBuildError(null);
// Reset navigation history and state
setCurrentPath('/');
@@ -464,13 +454,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframeLegacy();
refreshIframe();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
}, [projectId, checkForBuiltProject, refreshIframe]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -500,106 +490,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
};
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [copiedAll, setCopiedAll] = useState(false);
const [copiedBuildError, setCopiedBuildError] = useState(false);
const messages = isOpen ? getConsoleMessages() : [];
const messages = isLogsOpen ? getConsoleMessages() : [];
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 gap-2 relative"
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0 z-[9999]"
sideOffset={4}
>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
);
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const copyAllMessagesToClipboard = async () => {
try {
const allMessages = messages.map(msg => msg.message).join('\n');
await navigator.clipboard.writeText(allMessages);
setCopiedAll(true);
setTimeout(() => setCopiedAll(false), 2000);
} catch (error) {
console.error('Failed to copy all messages to clipboard:', error);
}
};
const messageCount = messages.length;
// Programmatically resize panels when isLogsOpen changes
useEffect(() => {
if (isLogsOpen) {
// Open logs panel to 40% and resize iframe to 60%
logsPanelRef.current?.resize(40);
iframePanelRef.current?.resize(60);
} else {
// Close logs panel and expand iframe to 100%
logsPanelRef.current?.resize(0);
iframePanelRef.current?.resize(100);
}
}, [isLogsOpen]);
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
@@ -656,7 +588,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
})}
disabled={isBuildLoading}
className="h-8 gap-2"
title="Build project"
title={t('buildButtonTooltip')}
>
{isBuildLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
@@ -671,45 +603,249 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
size="sm"
onClick={onToggleView}
className="h-8 gap-2"
title={t('codeButtonTooltip')}
>
<Code className="h-4 w-4" />
<span className="hidden lg:inline">Code</span>
</Button>
)}
<ConsoleDropdown />
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(!isLogsOpen)}
className={cn("h-8 gap-2 relative", isLogsOpen && "bg-muted")}
title={t('logsButtonTooltip')}
>
<Bug className="h-4 w-4" />
<span className="hidden lg:inline">Logs</span>
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
</div>
</div>
{/* Content area */}
<div className="flex-1 flex items-center justify-center bg-muted/30">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
<div className="flex-1 bg-muted/30 min-h-0 overflow-hidden">
<ResizablePanelGroup direction="vertical" className="h-full">
<ResizablePanel
ref={iframePanelRef}
defaultSize={isLogsOpen ? 60 : 100}
minSize={30}
className="min-h-0"
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
<div className="h-full flex items-center justify-center min-h-0">
{hasBuiltProject ? (
<div
className={cn(
"h-full transition-all duration-300 ease-in-out bg-background",
deviceMode === 'laptop' && "w-full",
deviceMode === 'tablet' && "w-full max-w-3xl shadow-lg",
deviceMode === 'phone' && "w-full max-w-sm shadow-lg"
)}
>
<iframe
key={projectId}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
/>
</div>
) : (
<div className="h-full w-full flex items-center justify-center bg-muted p-4">
<div className="text-center space-y-4 max-w-2xl w-full">
<div>
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
<p className="text-muted-foreground">
{t('buildProjectToSeePreview')}
</p>
</div>
{buildError && (
<div className="bg-destructive/10 border border-destructive/20 rounded-lg overflow-hidden text-left">
<div className="px-4 py-2 bg-destructive/20 border-b border-destructive/20 flex items-center justify-between">
<p className="font-semibold text-destructive text-sm">Build Failed</p>
<Button
variant="ghost"
size="sm"
onClick={async () => {
try {
await navigator.clipboard.writeText(buildError);
setCopiedBuildError(true);
setTimeout(() => setCopiedBuildError(false), 2000);
} catch (error) {
console.error('Failed to copy error to clipboard:', error);
}
}}
className="h-7 px-2 text-xs hover:bg-destructive/10"
>
{copiedBuildError ? (
<>
<Check className="h-3 w-3 mr-1.5" />
Copied
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
Copy
</>
)}
</Button>
</div>
<ScrollArea className="max-h-48">
<div className="overflow-x-auto">
<pre className="p-4 text-xs font-mono text-destructive whitespace-pre leading-relaxed">{buildError}</pre>
</div>
<ScrollBar orientation="horizontal" />
</ScrollArea>
</div>
)}
<Button
variant="outline"
onClick={() => {
setBuildError(null);
buildProject(undefined, {
onSuccess: () => {
setBuildError(null);
},
onError: (error) => {
console.error('Build failed:', error);
setBuildError(error instanceof Error ? error.message : String(error));
}
});
}}
disabled={isBuildLoading}
className="gap-2"
>
{isBuildLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Building...
</>
) : buildError ? (
<>
<RefreshCw className="h-4 w-4" />
Retry
</>
) : (
<>
<Hammer className="h-4 w-4" />
Build
</>
)}
</Button>
</div>
</div>
)}
</div>
</div>
)}
</ResizablePanel>
<ResizableHandle withHandle className={cn(!isLogsOpen && "hidden")} />
<ResizablePanel
ref={logsPanelRef}
defaultSize={isLogsOpen ? 40 : 0}
minSize={0}
maxSize={isLogsOpen ? undefined : 0}
className="min-h-0 min-w-0"
collapsible
collapsedSize={0}
>
{/* Logs Panel */}
<div className="h-full flex flex-col bg-background border-t overflow-hidden min-h-0 w-full min-w-0">
{/* Logs Header */}
<div className="h-12 px-4 border-b flex items-center justify-between flex-shrink-0">
<div className="flex items-center gap-2">
{hasConsoleErrors && (
<span className="h-2 w-2 rounded-full bg-red-500" />
)}
</div>
<div className="flex items-center gap-2">
{messageCount > 0 && (
<Button
variant="ghost"
size="sm"
onClick={copyAllMessagesToClipboard}
className="h-7 px-2 text-xs"
>
{copiedAll ? (
<>
<Check className="h-3 w-3 mr-1.5 text-success" />
{t('copied')}
</>
) : (
<>
<Copy className="h-3 w-3 mr-1.5" />
{t('copyAll')}
</>
)}
</Button>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setIsLogsOpen(false)}
className="h-7 w-7 p-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Logs Content */}
<div className="flex-1 min-h-0 overflow-hidden w-full">
<ScrollArea className="h-full w-full">
<div className="p-2 space-y-0 w-full min-w-0 max-w-full">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer w-full max-w-full"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div
className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words w-full min-w-0 max-w-full",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}
style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}
>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</ScrollArea>
</div>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
{/* Build loading overlay */}
@@ -0,0 +1,59 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import OpenAI from 'openai';
interface ToolsDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
}
export function ToolsDialog({ open, onOpenChange, tools }: ToolsDialogProps) {
const toolEntries = Object.entries(tools);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>Available Tools</DialogTitle>
<DialogDescription>
The current session's full list of available tools ({toolEntries.length} tools)
</DialogDescription>
</DialogHeader>
<ScrollArea className="h-[60vh] w-full pr-4">
<Accordion type="single" collapsible className="w-full space-y-2">
{toolEntries.map(([name, tool]) => {
const func = 'function' in tool ? tool.function : undefined;
return (
<AccordionItem key={name} value={name} className="border rounded-lg px-4">
<AccordionTrigger className="text-sm font-mono hover:no-underline py-3 outline-none focus:outline-none focus-visible:outline-none">
{name}
</AccordionTrigger>
<AccordionContent className="pt-2 pb-4">
<div className="space-y-3 text-sm">
<div>
<div className="font-semibold mb-1">Description:</div>
<div className="text-muted-foreground whitespace-pre-wrap">
{func?.description || 'No description available'}
</div>
</div>
{func?.parameters && (
<div>
<div className="font-semibold mb-1">Parameters:</div>
<pre className="text-xs bg-muted p-3 rounded-md overflow-x-auto">
{JSON.stringify(func.parameters, null, 2)}
</pre>
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
);
})}
</Accordion>
</ScrollArea>
</DialogContent>
</Dialog>
);
}
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ToolCallDisplay } from './ToolCallDisplay';
describe('ToolCallDisplay', () => {
describe('path stripping', () => {
it('should strip project prefix from absolute paths for read tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/mysite/src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="write"
toolArgs={{ filePath: '/projects/mysite/src/App.tsx', content: 'code' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote src/App.tsx')).toBeInTheDocument();
});
it('should strip project prefix from absolute paths for edit tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="edit"
toolArgs={{
filePath: '/projects/mysite/src/components/Header.tsx',
oldString: 'old',
newString: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/components/Header.tsx')).toBeInTheDocument();
});
it('should handle paths without project prefix', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: 'src/index.ts' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
it('should handle legacy text_editor_view tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_view"
toolArgs={{ path: '/projects/mysite/README.md' }}
state="completed"
result="File content"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Viewed README.md')).toBeInTheDocument();
});
it('should handle legacy text_editor_write tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_write"
toolArgs={{ path: '/projects/mysite/package.json', file_text: '{}' }}
state="completed"
result="File written"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Wrote package.json')).toBeInTheDocument();
});
it('should handle legacy text_editor_str_replace tool', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="text_editor_str_replace"
toolArgs={{
path: '/projects/mysite/src/utils.ts',
old_str: 'old',
new_str: 'new'
}}
state="completed"
result="File edited"
projectId="mysite"
/>
</TestApp>
);
expect(screen.getByText('Edited src/utils.ts')).toBeInTheDocument();
});
it('should handle different projects with same relative path', () => {
render(
<TestApp>
<ToolCallDisplay
toolName="read"
toolArgs={{ filePath: '/projects/another-project/src/index.ts' }}
state="completed"
result="File content"
projectId="another-project"
/>
</TestApp>
);
expect(screen.getByText('Viewed src/index.ts')).toBeInTheDocument();
});
});
});
+319 -66
View File
@@ -26,12 +26,15 @@ import {
Settings,
TriangleAlert,
X,
Search,
Clipboard,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ImageModelDialog } from '@/components/ImageModelDialog';
import { ImageLightbox } from '@/components/ImageLightbox';
import { useFSPaths } from '@/hooks/useFSPaths';
interface ToolInfo {
icon: LucideIcon;
@@ -45,6 +48,7 @@ interface ToolCallDisplayProps {
toolArgs: Record<string, unknown>;
state: 'calling' | 'waiting' | 'completed';
result?: string; // The tool result content (only for completed state)
projectId: string; // Current project ID for path display
}
// Component to show image generation errors inline
@@ -77,21 +81,95 @@ function ImageGenerationError() {
);
}
/**
* Strip project path prefix from absolute paths
* e.g., /projects/mysite/src/index.ts -> src/index.ts
*/
function stripProjectPrefix(path: string, projectId?: string, projectsPath = '/projects'): string {
if (!projectId) return path;
const projectPrefix = `${projectsPath}/${projectId}/`;
if (path === `${projectsPath}/${projectId}`) {
return '.';
} else if (path.startsWith(projectPrefix)) {
return path.slice(projectPrefix.length);
}
return path;
}
/**
* Get tool information including icon, title, and calling title
*/
function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo {
function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?: string, projectsPath?: string, result?: string): ToolInfo {
switch (toolName) {
case 'shell':
return {
icon: Terminal,
title: args.command ? String(args.command) : 'Shell Command',
callingTitle: args.command ? String(args.command) : 'Running Shell Command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell Command Failed',
title: args.command ? String(args.command) : 'Shell command',
callingTitle: args.command ? String(args.command) : 'Running shell command',
errorTitle: args.command ? `Failed: ${String(args.command)}` : 'Shell command failed',
};
// New tools (OpenCode-compatible names)
case 'read': {
const rawPath = args.filePath ? String(args.filePath) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const offset = typeof args.offset === 'number' ? args.offset : 0;
const limit = typeof args.limit === 'number' ? args.limit : undefined;
const lineInfo = (typeof offset === 'number' && typeof limit === 'number')
? ` (lines ${(offset || 0) + 1}-${limit ? offset + limit : ''})`
: '';
return {
icon: Eye,
title: `Viewed ${path}${lineInfo}`,
callingTitle: `Viewing ${path}${lineInfo}`,
errorTitle: `Failed to view ${path}${lineInfo}`,
};
}
case 'write': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'edit': {
const rawPath = args.filePath ? String(args.filePath) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'glob':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'File pattern search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching files',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
case 'grep':
return {
icon: Search,
title: args.pattern ? `Searched "${args.pattern}"` : 'Content search',
callingTitle: args.pattern ? `Searching "${args.pattern}"` : 'Searching content',
errorTitle: args.pattern ? `Failed to search ${args.pattern}` : 'Search failed',
};
// Legacy tools (kept for old chat history)
case 'text_editor_view': {
const path = args.path ? String(args.path) : 'File';
const rawPath = args.path ? String(args.path) : 'File';
const path = stripProjectPrefix(rawPath, projectId, projectsPath);
const hasLineRange = args.start_line || args.end_line;
const lineInfo = hasLineRange
? ` (lines ${args.start_line || 1}-${args.end_line || 'end'})`
@@ -104,21 +182,27 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
};
}
case 'text_editor_write':
case 'text_editor_write': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: FileText,
title: args.path ? `Wrote ${args.path}` : 'Wrote File',
callingTitle: args.path ? `Writing ${args.path}` : 'Writing File',
errorTitle: args.path ? `Failed to write ${args.path}` : 'Failed to Write File',
title: path ? `Wrote ${path}` : 'Wrote file',
callingTitle: path ? `Writing ${path}` : 'Writing file',
errorTitle: path ? `Failed to write ${path}` : 'Failed to write file',
};
}
case 'text_editor_str_replace':
case 'text_editor_str_replace': {
const rawPath = args.path ? String(args.path) : '';
const path = rawPath ? stripProjectPrefix(rawPath, projectId, projectsPath) : '';
return {
icon: Edit,
title: args.path ? `Edited ${args.path}` : 'Edited File',
callingTitle: args.path ? `Editing ${args.path}` : 'Editing File',
errorTitle: args.path ? `Failed to edit ${args.path}` : 'Failed to Edit File',
title: path ? `Edited ${path}` : 'Edited file',
callingTitle: path ? `Editing ${path}` : 'Editing file',
errorTitle: path ? `Failed to edit ${path}` : 'Failed to edit file',
};
}
case 'npm_add_package': {
const name = args.name ? String(args.name) : 'Package';
@@ -134,25 +218,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
case 'npm_remove_package':
return {
icon: PackageMinus,
title: args.name ? `Removed ${args.name}` : 'Removed Package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing Package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to Remove Package',
title: args.name ? `Removed ${args.name}` : 'Removed package',
callingTitle: args.name ? `Removing ${args.name}` : 'Removing package',
errorTitle: args.name ? `Failed to remove ${args.name}` : 'Failed to remove package',
};
case 'git_commit':
return {
icon: GitCommit,
title: args.message ? `Committed: ${args.message}` : 'Committed Changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing Changes',
errorTitle: 'Failed to Commit Changes',
title: args.message ? `Committed: ${args.message}` : 'Committed changes',
callingTitle: args.message ? `Committing: ${args.message}` : 'Committing changes',
errorTitle: 'Failed to commit changes',
};
case 'build_project':
return {
icon: Package,
title: 'Built Project',
callingTitle: 'Building Project',
errorTitle: 'Failed to Build Project',
title: 'Built project',
callingTitle: 'Building project',
errorTitle: 'Failed to build project',
};
case 'nostr_read_nip':
@@ -160,55 +244,55 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: BookOpen,
title: args.nip ? `Read NIP-${args.nip}` : 'Read NIP',
callingTitle: args.nip ? `Reading NIP-${args.nip}` : 'Reading NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to Read NIP',
errorTitle: args.nip ? `Failed to read NIP-${args.nip}` : 'Failed to read NIP',
};
case 'nostr_fetch_event':
return {
icon: Download,
title: args.identifier ? `Fetched ${String(args.identifier).slice(0, 16)}...` : 'Fetched Event',
callingTitle: args.identifier ? `Fetching ${String(args.identifier).slice(0, 16)}...` : 'Fetching Event',
errorTitle: args.identifier ? `Failed to fetch ${String(args.identifier).slice(0, 16)}...` : 'Failed to Fetch Event',
title: args.identifier ? `Viewed ${String(args.identifier).slice(0, 16)}...` : 'Viewed event',
callingTitle: args.identifier ? `Viewing ${String(args.identifier).slice(0, 16)}...` : 'Viewing event',
errorTitle: args.identifier ? `Failed to view ${String(args.identifier).slice(0, 16)}...` : 'Failed to view event',
};
case 'nostr_read_kind':
return {
icon: Hash,
title: args.kind !== undefined ? `Read Kind ${args.kind}` : 'Read Kind',
callingTitle: args.kind !== undefined ? `Reading Kind ${args.kind}` : 'Reading Kind',
errorTitle: args.kind !== undefined ? `Failed to read Kind ${args.kind}` : 'Failed to Read Kind',
title: args.kind !== undefined ? `Viewed kind ${args.kind}` : 'Viewed kind',
callingTitle: args.kind !== undefined ? `Viewing kind ${args.kind}` : 'Viewing kind',
errorTitle: args.kind !== undefined ? `Failed to view kind ${args.kind}` : 'Failed to view kind',
};
case 'nostr_read_tag':
return {
icon: Tag,
title: args.tag ? `Read Tag "${args.tag}"` : 'Read Tag',
callingTitle: args.tag ? `Reading Tag "${args.tag}"` : 'Reading Tag',
errorTitle: args.tag ? `Failed to read Tag "${args.tag}"` : 'Failed to Read Tag',
title: args.tag ? `Viewed tag "${args.tag}"` : 'Viewed tag',
callingTitle: args.tag ? `Viewing tag "${args.tag}"` : 'Viewing tag',
errorTitle: args.tag ? `Failed to view tag "${args.tag}"` : 'Failed to view tag',
};
case 'nostr_read_protocol':
return {
icon: Network,
title: args.doc ? `Read Protocol: ${args.doc}` : 'Read Protocol',
callingTitle: args.doc ? `Reading Protocol: ${args.doc}` : 'Reading Protocol',
errorTitle: args.doc ? `Failed to read Protocol: ${args.doc}` : 'Failed to Read Protocol',
title: args.doc ? `Viewed protocol ${args.doc}` : 'Viewed protocol',
callingTitle: args.doc ? `Viewing protocol ${args.doc}` : 'Viewing protocol',
errorTitle: args.doc ? `Failed to view protocol ${args.doc}` : 'Failed to view protocol',
};
case 'nostr_read_nips_index':
return {
icon: List,
title: 'Read NIPs Index',
callingTitle: 'Reading NIPs Index',
errorTitle: 'Failed to Read NIPs Index',
title: 'Viewed NIPs index',
callingTitle: 'Viewing NIPs index',
errorTitle: 'Failed to view NIPs index',
};
case 'nostr_generate_kind':
return {
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating Kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to Generate Kind',
title: args.range ? `Generated ${args.range} kind` : 'Generated kind',
callingTitle: args.range ? `Generating ${args.range} kind` : 'Generating kind',
errorTitle: args.range ? `Failed to generate ${args.range} kind` : 'Failed to generate kind',
};
case 'nostr_publish_events': {
@@ -217,58 +301,117 @@ function getToolInfo(toolName: string, args: Record<string, unknown>): ToolInfo
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event',
callingTitle: eventCount > 1 ? `Publishing ${eventCount} Nostr events` : 'Publishing Nostr event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to Publish Nostr Event',
errorTitle: eventCount > 1 ? `Failed to publish ${eventCount} Nostr events` : 'Failed to publish Nostr event',
};
}
case 'deploy_project':
return {
icon: Globe,
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed Project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying Project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to Deploy Project',
title: args.deployServer ? `Deployed to ${args.deployServer}` : 'Deployed project',
callingTitle: args.deployServer ? `Deploying to ${args.deployServer}` : 'Deploying project',
errorTitle: args.deployServer ? `Failed to deploy to ${args.deployServer}` : 'Failed to deploy project',
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console',
callingTitle: 'Reading Console',
errorTitle: 'Failed to Read Console',
title: 'Viewed console',
callingTitle: 'Viewing console',
errorTitle: 'Failed to view console',
};
case 'webfetch': {
const url = args.url ? String(args.url) : '';
return {
icon: Globe,
title: url ? `Viewed ${url}` : 'Viewed webpage',
callingTitle: url ? `Viewing ${url}` : 'Viewing webpage',
errorTitle: url ? `Failed to view ${url}` : 'Failed to view webpage',
};
}
case 'websearch': {
const query = args.query ? String(args.query) : '';
return {
icon: Search,
title: query ? `Searched "${query}"` : 'Web search',
callingTitle: query ? `Searching "${query}"` : 'Searching web',
errorTitle: query ? `Failed to search "${query}"` : 'Search failed',
};
}
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill',
callingTitle: args.name ? `Running Skill: ${args.name}` : 'Running Skill',
errorTitle: args.name ? `Skill Failed: ${args.name}` : 'Skill Failed',
callingTitle: args.name ? `Running skill: ${args.name}` : 'Running skill',
errorTitle: args.name ? `Skill failed: ${args.name}` : 'Skill failed',
};
case 'generate_image':
return {
icon: Image,
title: args.prompt ? String(args.prompt) : 'Generated Image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating Image',
errorTitle: 'Failed to Generate Image',
title: args.prompt ? String(args.prompt) : 'Generated image',
callingTitle: args.prompt ? String(args.prompt) : 'Generating image',
errorTitle: 'Failed to generate image',
};
case 'view_available_models':
return {
icon: Eye,
title: 'Viewed Available Models',
callingTitle: 'Viewing Available Models',
errorTitle: 'Failed to View Available Models',
title: 'Viewed available models',
callingTitle: 'Viewing available models',
errorTitle: 'Failed to view available models',
};
case 'configure_image_generation':
return {
icon: Settings,
title: args.model ? `Configured image model: ${args.model}` : 'Configured Image Generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring Image Generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to Configure Image Generation',
title: args.model ? `Configured image model: ${args.model}` : 'Configured image generation',
callingTitle: args.model ? `Configuring image model: ${args.model}` : 'Configuring image generation',
errorTitle: args.model ? `Failed to configure image model: ${args.model}` : 'Failed to configure image generation',
};
case 'todowrite':
case 'todoread': {
// Try to parse the result to get task counts for the title
let title = toolName === 'todowrite' ? 'Updated todo list' : 'Viewed todo list';
if (result) {
try {
const todos = JSON.parse(result);
if (Array.isArray(todos)) {
const activeTodos = todos.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completedTodos = todos.filter((x: { status: string }) => x.status === 'completed');
const inProgressTask = todos.find((x: { status: string }) => x.status === 'in_progress');
// Format: "[<completed>/<total>] <active-task>" if in_progress task exists
if (inProgressTask) {
const taskName = inProgressTask.content || 'Task';
const totalTasks = todos.length;
title = `[${completedTodos.length + 1}/${totalTasks}] ${taskName}`;
} else if (activeTodos.length === 0 && completedTodos.length > 0) {
// All tasks completed
title = `${completedTodos.length + 1} task${completedTodos.length !== 0 ? 's' : ''} completed`;
} else if (completedTodos.length === 0) {
// No completed tasks yet
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}`;
} else {
title = `${activeTodos.length} active task${activeTodos.length !== 1 ? 's' : ''}, ${completedTodos.length} completed`;
}
}
} catch {
// If parsing fails, use default title
}
}
return {
icon: Clipboard,
title,
callingTitle: toolName === 'todowrite' ? 'Updating todo list' : 'Viewing todo list',
errorTitle: toolName === 'todowrite' ? 'Failed to update todo list' : 'Failed to view todo list',
};
}
default: {
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
return {
@@ -299,12 +442,13 @@ function parseToolError(result: string | undefined, expectedToolName: string): s
/**
* Unified component for displaying tool calls in all states
*/
export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallDisplayProps) {
export function ToolCallDisplay({ toolName, toolArgs, state, result, projectId }: ToolCallDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const [imageLoadError, setImageLoadError] = useState(false);
const { projectsPath } = useFSPaths();
const toolInfo = getToolInfo(toolName, toolArgs);
const toolInfo = getToolInfo(toolName, toolArgs, projectId, projectsPath, result);
const IconComponent = toolInfo.icon;
// Check if this is an error result
@@ -342,19 +486,26 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
if (toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string') {
// Write tool expanded content (new and legacy)
if ((toolName === 'write' && typeof toolArgs.content === 'string') ||
(toolName === 'text_editor_write' && typeof toolArgs.file_text === 'string')) {
const content = toolName === 'write' ? String(toolArgs.content) : String(toolArgs.file_text);
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="whitespace-pre-wrap break-words font-mono">
{toolArgs.file_text}
{content}
</div>
</div>
);
}
if (toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string') {
const oldLines = String(toolArgs.old_str).split('\n');
const newLines = String(toolArgs.new_str).split('\n');
// Edit tool expanded content (new and legacy)
if ((toolName === 'edit' && typeof toolArgs.oldString === 'string' && typeof toolArgs.newString === 'string') ||
(toolName === 'text_editor_str_replace' && typeof toolArgs.old_str === 'string' && typeof toolArgs.new_str === 'string')) {
const oldStr = toolName === 'edit' ? String(toolArgs.oldString) : String(toolArgs.old_str);
const newStr = toolName === 'edit' ? String(toolArgs.newString) : String(toolArgs.new_str);
const oldLines = oldStr.split('\n');
const newLines = newStr.split('\n');
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
@@ -387,6 +538,56 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Read tool expanded content - parse and display file content nicely
if (toolName === 'read' || toolName === 'text_editor_view') {
// Parse the result to extract file content from <file> tags
const fileMatch = result.match(/<file>\n([\s\S]*?)\n\n\((.*?)\)\n<\/file>/);
if (fileMatch) {
const fileContent = fileMatch[1];
const footerMessage = fileMatch[2];
// Split content into lines and parse line numbers
const lines = fileContent.split('\n');
return (
<div className="mt-1 rounded border bg-background text-xs font-mono overflow-hidden">
<div className="max-h-96 overflow-y-auto">
<div>
{lines.map((line, idx) => {
// Parse line number and content (format: " 1| content")
const match = line.match(/^(\s*\d+)\|(.*)$/);
if (match) {
return (
<div key={idx} className="flex hover:bg-muted/30 transition-colors">
<div className="text-muted-foreground/60 select-none px-3 py-0.5 text-right min-w-[3rem] bg-muted/20">
{match[1].trim()}
</div>
<div className="flex-1 px-3 py-0.5 whitespace-pre-wrap break-words">
{match[2]}
</div>
</div>
);
}
// Fallback for lines that don't match expected format
return (
<div key={idx} className="px-3 py-0.5 whitespace-pre-wrap break-words">
{line}
</div>
);
})}
</div>
</div>
{footerMessage && (
<div className="px-3 py-1.5 bg-muted/30 border-t text-muted-foreground text-[10px]">
{footerMessage}
</div>
)}
</div>
);
}
// Fallback to default rendering if no <file> tags found
}
if (toolName === 'generate_image') {
// For generate_image, when expanded show the full prompt
return (
@@ -396,6 +597,58 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
);
}
// Todo tools expanded content
if (toolName === 'todowrite' || toolName === 'todoread') {
try {
const todos = JSON.parse(result);
if (!Array.isArray(todos)) {
throw new Error('Invalid todo format');
}
if (todos.length === 0) {
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
<div className="text-muted-foreground italic">No todos found</div>
</div>
);
}
// Find the first in_progress task for bold styling
const firstInProgressIndex = todos.findIndex((x: { status: string }) => x.status === 'in_progress');
return (
<div className="mt-1 rounded border bg-muted/30 text-xs overflow-hidden">
<div className="px-3 py-2 space-y-1">
{todos.map((todo: { id: string; content: string; status: string; priority: string }, index: number) => {
const isChecked = todo.status === 'completed' || todo.status === 'cancelled';
const isFirstInProgress = index === firstInProgressIndex;
return (
<div key={todo.id} className="flex items-start gap-2 py-1">
<input
type="checkbox"
checked={isChecked}
readOnly
className="mt-0.5 h-4 w-4 rounded border-gray-300 cursor-default"
/>
<span className={cn(
"flex-1 text-foreground",
isChecked && "line-through text-muted-foreground",
isFirstInProgress && "font-bold"
)}>
{todo.content}
</span>
</div>
);
})}
</div>
</div>
);
} catch {
// If parsing fails, fall through to default rendering
}
}
// Default rendering for other tools
return (
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
+1 -1
View File
@@ -251,7 +251,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
useEffect(() => {
if (target) {
setComment('Zapped from Shakespeare!');
setComment('Zapped with MKStack!');
}
}, [target]);
@@ -63,10 +63,10 @@ export function CloudflareDeployForm({
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: subdomainUrl }) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
fetch(corsProxy ? proxyUrl({ template: corsProxy, url: workersUrl }) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
+1 -1
View File
@@ -56,7 +56,7 @@ export function DenoDeployForm({
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
+3
View File
@@ -4,6 +4,7 @@ import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { DeploySteps } from './DeploySteps';
import { useTranslation } from 'react-i18next';
interface DeployButtonProps {
projectId: string;
@@ -14,6 +15,7 @@ interface DeployButtonProps {
export function DeployButton({ projectId, projectName, className, disabled }: DeployButtonProps) {
const [open, setOpen] = useState(false);
const { t } = useTranslation();
return (
<Popover open={open} onOpenChange={setOpen}>
@@ -24,6 +26,7 @@ export function DeployButton({ projectId, projectName, className, disabled }: De
className={cn("size-8 p-0 group", className)}
aria-label="Deploy project"
disabled={disabled}
title={t('deployButtonTooltip')}
>
<Rocket className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
</Button>
+105 -36
View File
@@ -16,7 +16,6 @@ import { useNostr } from '@nostrify/react';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useGit } from '@/hooks/useGit';
import { NostrURI } from '@/lib/NostrURI';
import { createRepositoryAnnouncementEvent } from '@/lib/announceRepository';
import { Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { PresetDeployProvider } from '@/lib/deploy/types';
@@ -27,6 +26,7 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
@@ -35,6 +35,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
/**
* Normalize a URL string to ensure it has a protocol
@@ -105,6 +106,14 @@ interface DenoDeployFormData {
projectName: string;
}
interface RailwayFormData {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}
export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -144,6 +153,13 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
const [railwayForm, setRailwayForm] = useState<RailwayFormData>({
workspaceId: '',
projectId: '',
environmentId: '',
serviceId: '',
projectName: projectName || projectId,
});
// Load project settings when component mounts
useEffect(() => {
@@ -248,6 +264,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
baseDomain: cloudflareProvider.baseDomain,
projectName: cloudflareForm.projectName || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
esmUrl: config.esmUrl,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider;
@@ -267,6 +284,23 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
if (!railwayProvider.apiKey) {
throw new Error('Railway API token is required');
}
adapter = new RailwayAdapter({
fs,
apiKey: railwayProvider.apiKey,
baseURL: railwayProvider.baseURL,
workspaceId: railwayForm.workspaceId || undefined,
projectId: railwayForm.projectId || undefined,
environmentId: railwayForm.environmentId || undefined,
serviceId: railwayForm.serviceId || undefined,
projectName: railwayForm.projectName || undefined,
corsProxy: railwayProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
}
@@ -326,6 +360,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
projectName: denoDeployForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'railway') {
await updateProjectSettings(selectedProviderId, {
type: 'railway',
url: result.url,
data: {
workspaceId: railwayForm.workspaceId || undefined,
projectId: result.metadata?.projectId as string | undefined,
environmentId: result.metadata?.environmentId as string | undefined,
serviceId: result.metadata?.serviceId as string | undefined,
},
});
}
setDeployResult(result);
@@ -341,47 +386,35 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
// Query for existing repository announcement
const existingRepos = await nostr.query(
[{ kinds: [30617], authors: [user.pubkey], '#d': [nostrURI.identifier], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
{ signal: AbortSignal.timeout(1500) }
);
if (existingRepos.length > 0) {
const existingEvent = existingRepos[0];
let changed = false;
let hasWebTag = false;
// Extract existing data from the event
const description = existingEvent.tags.find(([tagName]) => tagName === 'description')?.[1];
const webTag = existingEvent.tags.find(([tagName]) => tagName === 'web');
const existingWebUrls = webTag ? webTag.slice(1) : [];
const cloneTag = existingEvent.tags.find(([tagName]) => tagName === 'clone');
const cloneUrls = cloneTag ? cloneTag.slice(1) : [];
const relaysTag = existingEvent.tags.find(([tagName]) => tagName === 'relays');
const relays = relaysTag ? relaysTag.slice(1) : [];
const tTags = existingEvent.tags
.filter(([tagName]) => tagName === 't')
.map(([, value]) => value);
const eucTag = existingEvent.tags.find(([tagName, , marker]) => tagName === 'r' && marker === 'euc');
const earliestCommit = eucTag?.[1];
const name = existingEvent.tags.find(([tagName]) => tagName === 'name')?.[1];
const repoEvent = structuredClone(existingRepos[0]);
// Add deployment URL if not already present
const deploymentUrl = result.url;
const updatedWebUrls = existingWebUrls.includes(deploymentUrl)
? existingWebUrls
: [...existingWebUrls, deploymentUrl];
for (const tag of repoEvent.tags) {
if (tag[0] === 'web') {
if (tag[1] !== result.url) {
tag[1] = result.url;
changed = true;
hasWebTag = true;
}
}
}
// Create updated repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: nostrURI.identifier,
name,
description,
webUrls: updatedWebUrls,
cloneUrls,
relays,
tTags: tTags.length > 0 ? tTags : undefined,
earliestCommit,
});
if (!hasWebTag) {
repoEvent.tags.push(['web', result.url]);
changed = true;
}
// Publish the updated event
await publishEvent(eventTemplate);
// Publish updated repo event if deployment URL changed
if (changed) {
// Publish the updated event
await publishEvent(repoEvent);
}
}
}
} catch (err) {
@@ -406,6 +439,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
onClose();
};
@@ -437,6 +471,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDenoDeployForm({ projectName });
}, []);
const handleRailwayConfigChange = useCallback((config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => {
setRailwayForm(config);
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -542,6 +586,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
);
}
if (selectedProvider.type === 'railway') {
const railwayProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedWorkspaceId = savedConfig?.type === 'railway' ? savedConfig.data.workspaceId : undefined;
const savedProjectId = savedConfig?.type === 'railway' ? savedConfig.data.projectId : undefined;
const savedEnvironmentId = savedConfig?.type === 'railway' ? savedConfig.data.environmentId : undefined;
const savedServiceId = savedConfig?.type === 'railway' ? savedConfig.data.serviceId : undefined;
return (
<RailwayDeployForm
apiKey={railwayProvider.apiKey}
baseURL={railwayProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedWorkspaceId={savedWorkspaceId}
savedProjectId={savedProjectId}
savedEnvironmentId={savedEnvironmentId}
savedServiceId={savedServiceId}
onConfigChange={handleRailwayConfigChange}
corsProxy={railwayProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
};
@@ -718,7 +786,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
(selectedProvider.type === 'railway' && !railwayForm.workspaceId)
}
className="w-full"
>
+1 -1
View File
@@ -53,7 +53,7 @@ export function NetlifyDeployForm({
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
headers: {
+382
View File
@@ -0,0 +1,382 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface Workspace {
id: string;
name: string;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
services: {
edges: Array<{
node: {
id: string;
name: string;
};
}>;
};
}
interface RailwayDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedWorkspaceId?: string;
savedProjectId?: string;
savedEnvironmentId?: string;
savedServiceId?: string;
onConfigChange: (config: {
workspaceId: string;
projectId: string;
environmentId: string;
serviceId: string;
projectName?: string;
}) => void;
corsProxy?: string;
}
export function RailwayDeployForm({
apiKey,
baseURL = 'https://backboard.railway.com',
projectId,
projectName,
savedWorkspaceId,
savedProjectId,
savedEnvironmentId,
savedServiceId,
onConfigChange,
corsProxy,
}: RailwayDeployFormProps) {
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>('');
const [selectedProjectId, setSelectedProjectId] = useState<string>('');
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<string>('');
const [selectedServiceId, setSelectedServiceId] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchWorkspaces = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const url = `${baseURL}/graphql/v2`;
const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
if (!response.ok) {
throw new Error(`Failed to fetch workspaces: ${response.status} ${response.statusText}`);
}
const result = await response.json();
if (result.errors) {
throw new Error(`Railway API error: ${result.errors[0]?.message || 'Unknown error'}`);
}
const workspacesData: Workspace[] = result.data.me.workspaces;
setWorkspaces(workspacesData);
// Auto-select workspace if saved or if there's only one
if (savedWorkspaceId && workspacesData.some(w => w.id === savedWorkspaceId)) {
setSelectedWorkspaceId(savedWorkspaceId);
} else if (workspacesData.length === 1) {
setSelectedWorkspaceId(workspacesData[0].id);
}
// Auto-select project if saved
if (savedProjectId) {
setSelectedProjectId(savedProjectId);
}
// Auto-select environment if saved
if (savedEnvironmentId) {
setSelectedEnvironmentId(savedEnvironmentId);
}
// Auto-select service if saved
if (savedServiceId) {
setSelectedServiceId(savedServiceId);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch workspaces');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedWorkspaceId, savedProjectId, savedEnvironmentId, savedServiceId, corsProxy]);
useEffect(() => {
fetchWorkspaces();
}, [fetchWorkspaces]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectId === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectId, newProjectName, projectName, projectId]);
// Notify parent of configuration changes
useEffect(() => {
if (!selectedWorkspaceId || !selectedProjectId) {
return;
}
if (selectedProjectId === 'new') {
// Creating new project - only require workspace and project name
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: '',
environmentId: '',
serviceId: '',
projectName: newProjectName,
});
} else {
// Existing project - require environment and service
if (!selectedEnvironmentId || !selectedServiceId) {
return;
}
onConfigChange({
workspaceId: selectedWorkspaceId,
projectId: selectedProjectId,
environmentId: selectedEnvironmentId,
serviceId: selectedServiceId === 'new' ? '' : selectedServiceId,
});
}
}, [selectedWorkspaceId, selectedProjectId, selectedEnvironmentId, selectedServiceId, newProjectName, onConfigChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Workspace</Label>
<Skeleton className="h-10 w-full" />
</div>
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
</div>
);
}
const selectedWorkspace = workspaces.find(w => w.id === selectedWorkspaceId);
const projects = selectedWorkspace?.projects.edges.map(e => e.node) || [];
const selectedProject = projects.find(p => p.id === selectedProjectId);
const environments = selectedProject?.environments.edges.map(e => e.node) || [];
const services = selectedProject?.services.edges.map(e => e.node) || [];
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Workspace Selection */}
<div className="space-y-2">
<Label htmlFor="railway-workspace">Workspace</Label>
<Select value={selectedWorkspaceId} onValueChange={setSelectedWorkspaceId}>
<SelectTrigger id="railway-workspace">
<SelectValue placeholder="Select a workspace..." />
</SelectTrigger>
<SelectContent>
{workspaces.map((workspace) => (
<SelectItem key={workspace.id} value={workspace.id}>
{workspace.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Project Selection */}
{selectedWorkspaceId && (
<div className="space-y-2">
<Label htmlFor="railway-project">Project</Label>
<Select
value={selectedProjectId}
onValueChange={(value) => {
setSelectedProjectId(value);
setSelectedEnvironmentId('');
setSelectedServiceId('');
}}
>
<SelectTrigger id="railway-project">
<SelectValue placeholder="Select a project or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new project
</div>
</SelectItem>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* New Project Name */}
{selectedProjectId === 'new' && (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Project Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
A new project with a production environment and web service will be created when you deploy
</p>
</div>
)}
{/* Environment Selection */}
{selectedProjectId && selectedProjectId !== 'new' && environments.length > 0 && (
<div className="space-y-2">
<Label htmlFor="railway-environment">Environment</Label>
<Select value={selectedEnvironmentId} onValueChange={setSelectedEnvironmentId}>
<SelectTrigger id="railway-environment">
<SelectValue placeholder="Select an environment..." />
</SelectTrigger>
<SelectContent>
{environments.map((env) => (
<SelectItem key={env.id} value={env.id}>
{env.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Service Selection */}
{selectedProjectId && selectedProjectId !== 'new' && selectedEnvironmentId && (
<div className="space-y-2">
<Label htmlFor="railway-service">Service</Label>
<Select value={selectedServiceId} onValueChange={setSelectedServiceId}>
<SelectTrigger id="railway-service">
<SelectValue placeholder="Select a service or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new service
</div>
</SelectItem>
{services.map((service) => (
<SelectItem key={service.id} value={service.id}>
{service.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Project Info */}
{selectedProject && selectedProjectId !== 'new' && (
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedProject.name}</p>
<p className="text-xs text-muted-foreground">
{environments.length} environment(s), {services.length} service(s)
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://railway.app/project/${selectedProject.id}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
);
}
@@ -7,6 +7,7 @@ import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useFSPaths } from '@/hooks/useFSPaths';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
import { useTranslation } from 'react-i18next';
interface GitSyncButtonProps {
projectId: string;
@@ -18,6 +19,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { t } = useTranslation();
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
@@ -129,6 +131,7 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
title={t('cloudSyncButtonTooltip')}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
@@ -2,7 +2,6 @@ import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useGit } from '@/hooks/useGit';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -20,6 +19,9 @@ import type { NostrEvent } from '@nostrify/nostrify';
import { NostrURI } from '@/lib/NostrURI';
import { useGitAutosync } from '@/hooks/useGitAutosync';
import { ArrowUp } from 'lucide-react';
import { ForcePushDialog } from './ForcePushDialog';
import { SyncStepError } from './SyncStepError';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
// Helper function to convert kebab-case to Title Case
function kebabToTitleCase(str: string): string {
@@ -41,7 +43,8 @@ export function ConfigureRepoStep({
const [repoName, setRepoName] = useState(kebabToTitleCase(projectId));
const [isRepoNameManuallyEdited, setIsRepoNameManuallyEdited] = useState(false);
const [isPushing, setIsPushing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [error, setError] = useState<Error | null>(null);
const [showForcePushDialog, setShowForcePushDialog] = useState(false);
const { user } = useCurrentUser();
const { git } = useGit();
@@ -55,6 +58,7 @@ export function ConfigureRepoStep({
const { mutateAsync: publishEvent } = useNostrPublish();
const { fs } = useFS();
const { config } = useAppContext();
const { settings: projectDeploySettings } = useProjectDeploySettings(projectId);
// Auto-update repo name when repo identifier changes (unless manually edited)
useEffect(() => {
@@ -74,9 +78,10 @@ export function ConfigureRepoStep({
setIsRepoNameManuallyEdited(true);
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
// Shared push logic for both initial push and force push
const executePush = async (force: boolean = false) => {
// Store the URL we're trying to add so we can remove it on error
let remoteAdded = false;
try {
if (selectedProvider.id === 'nostr') {
@@ -166,6 +171,15 @@ export function ConfigureRepoStep({
tTags.push(template.name);
}
// Get deployment URL from project settings if available
let webUrls: string[] | undefined;
if (projectDeploySettings.currentProvider) {
const currentProviderConfig = projectDeploySettings.providers[projectDeploySettings.currentProvider];
if (currentProviderConfig?.url) {
webUrls = [currentProviderConfig.url];
}
}
// Create the repository announcement event
const eventTemplate = createRepositoryAnnouncementEvent({
repoId: repoIdentifier,
@@ -173,6 +187,7 @@ export function ConfigureRepoStep({
cloneUrls: [...cloneUrls],
relays: [...relays],
tTags,
webUrls,
});
// Publish the event
@@ -196,12 +211,14 @@ export function ConfigureRepoStep({
url: nostrURI.toString(),
force: true,
});
remoteAdded = true;
// Push to Nostr (the rest of the Nostr logic is handled internally by git.push)
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
} else {
// Validate repository URL
@@ -216,12 +233,14 @@ export function ConfigureRepoStep({
url: repositoryUrl,
force: true, // Override if exists
});
remoteAdded = true;
// Push to remote
await git.push({
dir,
remote: 'origin',
ref: gitStatus?.currentBranch || 'main',
force,
});
}
@@ -238,8 +257,45 @@ export function ConfigureRepoStep({
// Show success state
onSuccess();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to push';
setError(message);
const error = err instanceof Error ? err : new Error(force ? 'Failed to force push' : 'Failed to push');
// If we added the remote but push failed, remove it
if (remoteAdded) {
try {
await git.deleteRemote({ dir, remote: 'origin' });
} catch {
// Ignore errors when cleaning up remote
}
}
throw error; // Re-throw so caller can handle
}
};
const handlePushInitial = async () => {
setIsPushing(true);
setError(null);
try {
await executePush(false);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to push');
setError(error);
} finally {
setIsPushing(false);
}
};
const handleForcePush = async () => {
setIsPushing(true);
setError(null);
setShowForcePushDialog(false);
try {
await executePush(true);
} catch (err) {
const error = err instanceof Error ? err : new Error('Failed to force push');
setError(error);
} finally {
setIsPushing(false);
}
@@ -343,9 +399,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -360,6 +420,13 @@ export function ConfigureRepoStep({
{isPushing ? 'Pushing...' : 'Push'}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
@@ -386,9 +453,13 @@ export function ConfigureRepoStep({
</div>
{error && (
<Alert variant="destructive">
<AlertDescription className="text-sm">{error}</AlertDescription>
</Alert>
<SyncStepError
error={error}
onDismiss={() => setError(null)}
onForcePush={() => setShowForcePushDialog(true)}
remoteName={selectedProvider.name}
context="configure"
/>
)}
<div className="flex gap-2">
@@ -407,6 +478,13 @@ export function ConfigureRepoStep({
)}
</Button>
</div>
<ForcePushDialog
open={showForcePushDialog}
onOpenChange={setShowForcePushDialog}
onConfirm={handleForcePush}
remoteName={selectedProvider.name}
/>
</div>
);
}
+1 -1
View File
@@ -154,7 +154,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
if (url.protocol === 'nostr:') {
const nostrUri = await NostrURI.parse(url.href);
return ngitWebUrl(config.ngitWebUrl, nostrUri);
return ngitWebUrl({ template: config.ngitWebUrl, nostrURI: nostrUri });
}
return null;
+44 -10
View File
@@ -8,14 +8,16 @@ import { getSentryInstance } from '@/lib/sentry';
interface SyncStepErrorProps {
error: Error;
onDismiss: () => void;
onForcePull: () => void;
onForcePull?: () => void;
onForcePush: () => void;
onPull: () => void;
remoteUrl: URL;
onPull?: () => void;
remoteUrl?: URL;
remoteName: string;
/** Context for error messages - 'sync' for existing remotes, 'configure' for initial setup */
context?: 'sync' | 'configure';
}
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl }: SyncStepErrorProps) {
export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPull, remoteName, remoteUrl, context = 'sync' }: SyncStepErrorProps) {
const renderForcePullButton = () => (
<Button
variant="outline"
@@ -104,17 +106,23 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
// PushRejectedError - remote has changes
if (error instanceof GitErrors.PushRejectedError) {
// Different message based on context
const message = context === 'configure'
? `The repository on ${remoteName} is not empty. You'll need to force push to overwrite it with your local project.`
: `Push rejected. The remote repository has changes you don't have locally. Try pulling first.`;
return (
<Alert variant="destructive">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<AlertDescription className="text-sm flex-1">
Push rejected. The remote repository has changes you don't have locally. Try pulling first.
{message}
</AlertDescription>
{renderDismissButton()}
</div>
<div className="flex gap-2">
{renderPullButton()}
{/* Only show Pull button in sync context (not during initial configure) */}
{context === 'sync' && onPull && renderPullButton()}
{renderForcePushButton()}
</div>
</div>
@@ -126,17 +134,43 @@ export function SyncStepError({ error, onDismiss, onForcePull, onForcePush, onPu
if (error instanceof GitErrors.HttpError) {
let message: React.ReactNode = `HTTP Error: ${error.data.statusCode} ${error.data.statusMessage}`;
if (remoteUrl.protocol === 'nostr:') {
// Check if remoteUrl is a Nostr URL
if (remoteUrl?.protocol === 'nostr:') {
// This should never happen
getSentryInstance()?.captureException(error);
message = `There was an HTTP (${error.data.statusCode}) error communicating with Nostr Git servers.`
} else if (remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
} else if (remoteUrl && remoteUrl.protocol !== 'http:' && remoteUrl.protocol !== 'https:') {
// Handle standard HTTP errors based on status code
switch (error.data.statusCode) {
case 401:
message = <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
message = context === 'configure'
? <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>
: <>Your API token for {remoteName} is probably invalid or expired. Please try logging out and back into {remoteName} in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
message = context === 'configure'
? <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>
: <>You don't have permission to access this repository on {remoteName}. Try checking your permissions on <a href={remoteUrl.origin} target="_blank" className="underline">{remoteName}</a>.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
} else {
// No remoteUrl available or it's a standard HTTP/HTTPS URL
switch (error.data.statusCode) {
case 401:
message = <>Your credentials for {remoteName} are invalid or expired. Please check your login in <Link to="/settings/git" className="underline">Git Settings</Link>.</>;
break;
case 403:
message = <>You don't have permission to push to this repository on {remoteName}. Make sure the repository exists and you have write access.</>;
break;
case 404:
if (context === 'configure') {
message = <>Repository not found on {remoteName}. Make sure you've created the repository first and the URL is correct.</>;
}
break;
}
}
+1
View File
@@ -7,6 +7,7 @@ export interface AIProvider {
apiKey?: string;
nostr?: boolean;
proxy?: boolean;
openSecret?: string;
}
export interface MCPServer {
+8 -1
View File
@@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export interface RailwayProvider extends BaseDeployProvider {
type: 'railway';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export interface DeploySettings {
providers: DeployProvider[];
+11 -5
View File
@@ -46,8 +46,10 @@ export function useAIChat({
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
const initSession = useCallback(async () => {
setIsLoadingHistory(true);
const initSession = useCallback(async (showLoading = true) => {
if (showLoading) {
setIsLoadingHistory(true);
}
try {
// Load or update session
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
@@ -59,7 +61,9 @@ export function useAIChat({
setLastInputTokens(session.lastInputTokens || 0);
setLastFinishReason(session.lastFinishReason ?? null);
} finally {
setIsLoadingHistory(false);
if (showLoading) {
setIsLoadingHistory(false);
}
}
}, [sessionManager, projectId, tools, customTools, maxSteps]);
@@ -129,7 +133,8 @@ export function useAIChat({
providerModel: string
) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
@@ -142,7 +147,8 @@ export function useAIChat({
const startGeneration = useCallback(async (providerModel: string) => {
try {
await initSession();
// Ensure session is loaded (without showing loading state)
await initSession(false);
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
+5 -14
View File
@@ -13,7 +13,7 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'followed-repositories', followedPubkeys],
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
queryFn: async (): Promise<Repository[]> => {
if (followedPubkeys.length === 0) {
return [];
@@ -50,19 +50,10 @@ export function useFollowedRepositories(followedPubkeys: string[] = []) {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
const webTag = event.tags.find(tag => tag[0] === 'web');
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
+1 -1
View File
@@ -30,7 +30,7 @@ export function useGitHubOAuth() {
redirectUri: window.location.origin + '/oauth/github',
usePKCE: true, // GitHub supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.github.com/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+1 -1
View File
@@ -30,7 +30,7 @@ export function useNetlifyOAuth() {
redirectUri: window.location.origin + '/oauth/netlify',
usePKCE: false, // Netlify doesn't support PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.netlify.com/api/v1/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
+4 -2
View File
@@ -5,12 +5,14 @@ import { useCurrentUser } from "./useCurrentUser";
import type { NostrEvent } from "@nostrify/nostrify";
export function useNostrPublish(): UseMutationResult<NostrEvent> {
type NostrEventInput = Pick<NostrEvent, 'kind' | 'content'> & Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
export function useNostrPublish(): UseMutationResult<NostrEvent, Error, NostrEventInput> {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
mutationFn: async (t: NostrEventInput) => {
if (user) {
const tags = t.tags ?? [];
+1 -1
View File
@@ -169,7 +169,7 @@ export function useOAuth(config: OAuthConfig) {
}
// Exchange code for access token
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
const tokenUrl = proxyUrl({ template: corsProxy, url: config.tokenUrl });
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
-91
View File
@@ -1,91 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OGMetadata {
image: string | null;
description: string | null;
}
/**
* Hook to fetch Open Graph metadata from a web URL using CORS proxy
* @param webUrl - The web URL to fetch OG metadata from
* @returns Query result with OG image URL and description
*/
export function useOGImage(webUrl?: string) {
const { config } = useAppContext();
return useQuery({
queryKey: ['og-metadata', webUrl],
queryFn: async (): Promise<OGMetadata> => {
if (!webUrl) {
return { image: null, description: null };
}
try {
// Use CORS proxy to fetch the HTML
const proxiedUrl = proxyUrl(config.corsProxy, webUrl);
const response = await fetch(proxiedUrl, {
signal: AbortSignal.timeout(5000),
});
if (!response.ok) {
return { image: null, description: null };
}
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Extract OG image
let ogImage: string | null = null;
const ogImageMeta = doc.querySelector('meta[property="og:image"]')?.getAttribute('content');
if (ogImageMeta) {
try {
ogImage = new URL(ogImageMeta, webUrl).href;
} catch {
ogImage = ogImageMeta.startsWith('http') ? ogImageMeta : null;
}
}
// Fallback to twitter:image if og:image not found
if (!ogImage) {
const twitterImage = doc.querySelector('meta[name="twitter:image"]')?.getAttribute('content');
if (twitterImage) {
try {
ogImage = new URL(twitterImage, webUrl).href;
} catch {
ogImage = twitterImage.startsWith('http') ? twitterImage : null;
}
}
}
// Extract OG description
let ogDescription: string | null = null;
const ogDescriptionMeta = doc.querySelector('meta[property="og:description"]')?.getAttribute('content');
if (ogDescriptionMeta) {
ogDescription = ogDescriptionMeta.trim();
}
// Fallback to twitter:description if og:description not found
if (!ogDescription) {
const twitterDescription = doc.querySelector('meta[name="twitter:description"]')?.getAttribute('content');
if (twitterDescription) {
ogDescription = twitterDescription.trim();
}
}
return {
image: ogImage,
description: ogDescription || null,
};
} catch (error) {
console.warn('Failed to fetch OG metadata:', error);
return { image: null, description: null };
}
},
enabled: !!webUrl,
staleTime: 1000 * 60 * 60, // 1 hour
retry: 1,
});
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPlugins, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPluginSkills } from '@/lib/skills';
import { useGit } from './useGit';
import { join } from 'path-browserify';
+13
View File
@@ -52,6 +52,17 @@ const denoDeployProjectConfigSchema = z.object({
}),
});
const railwayProjectConfigSchema = z.object({
type: z.literal('railway'),
url: z.string(),
data: z.object({
workspaceId: z.string().optional(),
projectId: z.string().optional(),
environmentId: z.string().optional(),
serviceId: z.string().optional(),
}),
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
nsiteProjectConfigSchema,
@@ -59,6 +70,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [
vercelProjectConfigSchema,
cloudflareProjectConfigSchema,
denoDeployProjectConfigSchema,
railwayProjectConfigSchema,
]);
const projectDeploySettingsSchema = z.object({
@@ -72,6 +84,7 @@ export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
export type CloudflareProjectConfig = z.infer<typeof cloudflareProjectConfigSchema>;
export type DenoDeployProjectConfig = z.infer<typeof denoDeployProjectConfigSchema>;
export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
+4 -13
View File
@@ -55,19 +55,10 @@ export function useUserRepositories(userPubkey?: string) {
try {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
// Extract multi-value tags correctly (all values are in a single tag per NIP-34)
const webTag = event.tags.find(tag => tag[0] === 'web');
const webUrls = webTag ? webTag.slice(1).filter(Boolean) : [];
const cloneTag = event.tags.find(tag => tag[0] === 'clone');
const cloneUrls = cloneTag ? cloneTag.slice(1).filter(Boolean) : [];
const relaysTag = event.tags.find(tag => tag[0] === 'relays');
const relays = relaysTag ? relaysTag.slice(1).filter(Boolean) : [];
const maintainersTag = event.tags.find(tag => tag[0] === 'maintainers');
const maintainers = maintainersTag ? maintainersTag.slice(1).filter(Boolean) : [];
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
+1 -1
View File
@@ -34,7 +34,7 @@ export function useVercelOAuth() {
redirectUri: window.location.origin + '/oauth/vercel',
usePKCE: false, // Vercel doesn't require PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
const userUrl = proxyUrl({ template: corsProxy, url: 'https://api.vercel.com/v2/user' });
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
-371
View File
@@ -1,371 +0,0 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { KindGenerator } from './KindGenerator.ts';
const __dirname = dirname(fileURLToPath(import.meta.url));
describe('KindGenerator', () => {
it('should extract used kinds from real NIPs fixture', () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Check that some expected kinds are extracted from the real NIPs index
const expectedKinds = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
20,
21,
22,
30,
31,
32,
33,
40,
41,
42,
43,
44,
62,
64,
818,
1018,
1021,
1022,
1040,
1059,
1063,
1068,
1111,
1311,
1337,
1617,
1621,
1622,
1971,
1984,
1985,
1986,
1987,
2003,
2004,
2022,
4550,
7000,
7374,
7375,
7376,
9041,
9321,
9467,
9734,
9735,
9802,
10000,
10001,
10002,
10003,
10004,
10005,
10006,
10007,
10009,
10012,
10013,
10015,
10019,
10020,
10030,
10050,
10063,
10096,
10166,
13194,
17375,
21000,
22242,
23194,
23195,
24133,
24242,
27235,
30000,
30001,
30002,
30003,
30004,
30005,
30007,
30008,
30009,
30015,
30017,
30018,
30019,
30020,
30023,
30024,
30030,
30040,
30041,
30063,
30078,
30166,
30267,
30311,
30315,
30388,
30402,
30403,
30617,
30618,
30818,
30819,
31234,
31388,
31890,
31922,
31923,
31924,
31925,
31989,
31990,
32267,
34550,
38383,
39089,
39092,
39701,
];
for (const kind of expectedKinds) {
expect(usedKinds.has(kind)).toBe(true);
}
// Check that ranges are properly extracted
// `5000`-`5999` should add all numbers from 5000 to 5999
for (let i = 5000; i <= 5999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `6000`-`6999` should add all numbers from 6000 to 6999
for (let i = 6000; i <= 6999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `9000`-`9030` should add all numbers from 9000 to 9030
for (let i = 9000; i <= 9030; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `39000-9` should add all numbers from 39000 to 39009
for (let i = 39000; i <= 39009; i++) {
expect(usedKinds.has(i)).toBe(true);
}
// `1630`-`1633` should add all numbers from 1630 to 1633
for (let i = 1630; i <= 1633; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should extract used kinds from mock data', () => {
const mockNipsIndex = `
## Event Kinds
| kind | description | NIP |
| ------------- | ------------------------------- | -------------------------------------- |
| \`0\` | User Metadata | [01](01.md) |
| \`1\` | Short Text Note | [10](10.md) |
| \`3\` | Follows | [02](02.md) |
| \`1000\`-\`1999\` | Custom Range | [test](test.md) |
| \`30000\` | Addressable Event | [51](51.md) |
`;
const usedKinds = KindGenerator.extractUsedKinds(mockNipsIndex);
// Check individual kinds
expect(usedKinds.has(0)).toBe(true);
expect(usedKinds.has(1)).toBe(true);
expect(usedKinds.has(3)).toBe(true);
expect(usedKinds.has(30000)).toBe(true);
// Check range
for (let i = 1000; i <= 1999; i++) {
expect(usedKinds.has(i)).toBe(true);
}
});
it('should get kind range info correctly', () => {
const regularRange = KindGenerator.getKindRangeInfo('regular');
expect(regularRange.min).toBe(1000);
expect(regularRange.max).toBe(9999);
expect(regularRange.name).toBe('Regular Events');
const replaceableRange = KindGenerator.getKindRangeInfo('replaceable');
expect(replaceableRange.min).toBe(10000);
expect(replaceableRange.max).toBe(19999);
const ephemeralRange = KindGenerator.getKindRangeInfo('ephemeral');
expect(ephemeralRange.min).toBe(20000);
expect(ephemeralRange.max).toBe(29999);
const addressableRange = KindGenerator.getKindRangeInfo('addressable');
expect(addressableRange.min).toBe(30000);
expect(addressableRange.max).toBe(39999);
});
it('should generate available kinds in correct ranges', () => {
const usedKinds = new Set([1000, 1001, 1002, 10000, 10001, 30000, 30001]);
// Test regular range
const regularKind = KindGenerator.generateAvailableKind(
'regular',
usedKinds,
);
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
// Check new constraints
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
// Check buffer constraint - should not be within 2 of any used kind
for (const usedKind of usedKinds) {
const distance = Math.abs(regularKind - usedKind);
expect(distance > 2).toBe(true);
}
// Test replaceable range
const replaceableKind = KindGenerator.generateAvailableKind(
'replaceable',
usedKinds,
);
expect(replaceableKind >= 10000 && replaceableKind <= 19999).toBe(true);
expect(usedKinds.has(replaceableKind)).toBe(false);
expect(replaceableKind % 2 !== 0).toBe(true);
expect(replaceableKind % 5 !== 0).toBe(true);
// Test ephemeral range
const ephemeralKind = KindGenerator.generateAvailableKind(
'ephemeral',
usedKinds,
);
expect(ephemeralKind >= 20000 && ephemeralKind <= 29999).toBe(true);
expect(usedKinds.has(ephemeralKind)).toBe(false);
expect(ephemeralKind % 2 !== 0).toBe(true);
expect(ephemeralKind % 5 !== 0).toBe(true);
// Test addressable range
const addressableKind = KindGenerator.generateAvailableKind(
'addressable',
usedKinds,
);
expect(addressableKind >= 30000 && addressableKind <= 39999).toBe(true);
expect(usedKinds.has(addressableKind)).toBe(false);
expect(addressableKind % 2 !== 0).toBe(true);
expect(addressableKind % 5 !== 0).toBe(true);
});
it('should respect buffer constraints when generating kinds', () => {
// Test buffer constraint specifically
const usedKinds = new Set([1007, 1013, 1019]); // Use odd numbers that aren't multiples of 5
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should be in range
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
// Should be odd
expect(regularKind % 2 !== 0).toBe(true);
// Should not be multiple of 5
expect(regularKind % 5 !== 0).toBe(true);
// Should not be within buffer of used kinds
const forbiddenNumbers = new Set([
1005, 1006, 1007, 1008, 1009, // around 1007
1011, 1012, 1013, 1014, 1015, // around 1013
1017, 1018, 1019, 1020, 1021, // around 1019
]);
expect(forbiddenNumbers.has(regularKind)).toBe(false);
});
it('should handle edge cases with many used kinds', () => {
// Test with many used kinds to ensure we still find valid ones
const usedKinds = new Set<number>();
// Fill most even numbers and multiples of 5 in a small range
for (let i = 1000; i <= 1100; i++) {
if (i % 2 === 0 || i % 5 === 0) {
usedKinds.add(i);
}
}
const regularKind = KindGenerator.generateAvailableKind('regular', usedKinds);
// Should still find a valid kind
expect(regularKind >= 1000 && regularKind <= 9999).toBe(true);
expect(regularKind % 2 !== 0).toBe(true);
expect(regularKind % 5 !== 0).toBe(true);
expect(usedKinds.has(regularKind)).toBe(false);
});
it('should generate random kinds with good distribution', { timeout: 10000 }, () => {
const nipsIndex = readFileSync(join(__dirname, 'fixtures', 'NIPs.md'), 'utf-8');
const usedKinds = KindGenerator.extractUsedKinds(nipsIndex);
// Generate many kinds and check distribution
const results = new Map<number, number>();
const iterations = 50; // Reduced from 100 to 50 for performance
for (let i = 0; i < iterations; i++) {
const kind = KindGenerator.generateAvailableKind('regular', usedKinds);
results.set(kind, (results.get(kind) || 0) + 1);
// Verify constraints on each generated kind
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
expect(usedKinds.has(kind)).toBe(false);
}
// Check that we get good variety (at least 5 unique kinds in 50 iterations)
// Reduced expectations due to fewer iterations
expect(results.size).toBeGreaterThanOrEqual(5);
// Check that no single kind dominates (no kind should appear more than 50% of the time)
// Increased threshold due to fewer iterations
const maxFrequency = Math.max(...results.values());
const maxFrequencyPercent = (maxFrequency / iterations) * 100;
expect(maxFrequencyPercent).toBeLessThanOrEqual(50);
// Check that all generated kinds follow our constraints
for (const [kind] of results) {
expect(kind % 2 !== 0).toBe(true);
expect(kind % 5 !== 0).toBe(true);
// Check buffer constraint
for (const usedKind of usedKinds) {
const distance = Math.abs(kind - usedKind);
expect(distance > 2).toBe(true);
}
}
});
});
+39 -2
View File
@@ -661,7 +661,7 @@ export class SessionManager {
console.error('AI generation error:', error);
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
if (error instanceof OpenAI.APIUserAbortError || (error instanceof Error && error.name === 'AbortError')) {
return; // User cancelled
}
@@ -720,13 +720,50 @@ export class SessionManager {
this.emit('finishReasonChanged', projectId, null);
}
/**
* Check if content exceeds size/line limits
*/
private exceedsLimits(content: string): boolean {
const MAX_SIZE_BYTES = 50 * 1024; // 50 KiB
const MAX_LINES = 2000;
const sizeBytes = new Blob([content]).size;
const lineCount = content.split('\n').length;
return sizeBytes > MAX_SIZE_BYTES || lineCount > MAX_LINES;
}
/**
* Save content to tmpDir and return the file path
*/
private async saveToTmpFile(projectId: string, content: string, toolCallId: string): Promise<string> {
const config = this.getConfig();
const timestamp = Date.now();
const filename = `tool-output-${toolCallId}-${timestamp}.txt`;
const filepath = `${config.fsPathTmp}/${filename}`;
await this.fs.writeFile(filepath, content, 'utf8');
return filepath;
}
/**
* Helper to add tool messages and update conversation
*/
private async addToolMessage(projectId: string, toolCallId: string, content: string): Promise<void> {
let finalContent = content;
// Check if content exceeds limits
if (this.exceedsLimits(content)) {
// Save full content to tmp file
const filepath = await this.saveToTmpFile(projectId, content, toolCallId);
// Create placeholder message
finalContent = `The tool call succeeded but the output was truncated. Full output saved to: ${filepath}\nUse \`grep\` to search the full content or \`read\` with offset/limit to view specific sections.`;
}
const toolMessage: AIMessage = {
role: 'tool',
content,
content: finalContent,
tool_call_id: toolCallId
};
+9 -5
View File
@@ -12,15 +12,19 @@ import { proxyUrl } from './proxyUrl';
* If the provider has proxy enabled, requests will be proxied through the corsProxy.
*/
export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: string): OpenAI {
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
const openai = new OpenAI({
baseURL: provider.baseURL,
apiKey: provider.apiKey ?? '',
dangerouslyAllowBrowser: true,
};
const openai = new OpenAI({
...baseConfig,
fetch: async (input, init) => {
// OpenSecret auth
// https://docs.opensecret.cloud/docs/maple-ai/
if (provider.openSecret) {
const { createCustomFetch } = await import('@opensecret/react');
return createCustomFetch({ apiKey: provider.apiKey, apiUrl: provider.openSecret })(input, init);
}
let request = new Request(input, init);
// Add OpenRouter headers
@@ -47,7 +51,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
// If proxy is enabled and we have a CORS proxy URL, modify the request URL
if (provider.proxy && corsProxy) {
request = new Request(proxyUrl(corsProxy, request.url), request);
request = new Request(proxyUrl({ template: corsProxy, url: request.url }), request);
}
return fetch(request);
+16 -7
View File
@@ -6,6 +6,7 @@ export interface PresetProvider {
nostr?: boolean;
tosURL?: string;
proxy?: boolean;
openSecret?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -16,13 +17,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://ai.shakespeare.diy/terms",
nostr: true,
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "opencode",
name: "OpenCode Zen",
@@ -31,6 +25,21 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://opencode.ai/legal/terms-of-service",
proxy: true,
},
{
id: "maple",
name: "Maple AI",
baseURL: "https://enclave.trymaple.ai/v1",
apiKeysURL: "https://trymaple.ai/",
tosURL: "https://opensecret.cloud/terms",
openSecret: "https://enclave.trymaple.ai",
},
{
id: "openrouter",
name: "OpenRouter",
baseURL: "https://openrouter.ai/api/v1",
apiKeysURL: "https://openrouter.ai/settings/keys",
tosURL: "https://openrouter.ai/terms",
},
{
id: "ppq",
name: "PayPerQ",
+21 -1
View File
@@ -158,7 +158,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
let current: string | undefined = base;
while (current && current.length) {
// Remove the last package from the path (handling scoped packages like @scope/name)
const next = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
const next: string = current.replace(/\/node_modules\/(@[^/]+\/)?[^/]+$/, "");
if (next === current) break;
current = next;
const candidate = `${current}/node_modules/${name}`;
@@ -226,6 +226,11 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
};
case "crypto":
return {
path: `${esmUrl}/crypto-browserify?target=${target ?? "esnext"}`,
namespace: "esm",
};
default:
return {
errors: [{ text: `Module not found: ${args.path}` }],
@@ -260,6 +265,19 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// not a URL; continue
}
// Check if this is a file: dependency
const allDeps = {
...packageJson.dependencies,
...packageJson.devDependencies,
...packageJson.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Let fsPlugin handle file: dependencies
return;
}
// Determine importer lock path (breadcrumb)
const importerLockPath = getImporterLockPath(args.importer);
@@ -430,6 +448,8 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
if (contentType) {
if (contentType === "application/javascript") {
loader = "js";
} else if (contentType === "application/json") {
loader = "json";
} else if (contentType === "text/css") {
loader = "css";
} else if (contentType === "application/wasm") {
+94 -13
View File
@@ -10,14 +10,21 @@ interface TsConfig {
};
}
interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
interface FsPluginOptions {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig } = options;
const { fs, cwd, tsconfig, packageJson } = options;
return {
name: "fs",
@@ -30,27 +37,66 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
});
build.onResolve({ filter: /.*/ }, async (args) => {
// Skip resolving paths from external URLs
// Skip resolving paths from external URLs (but not fs: namespace)
if (/^https?:\/\//.test(args.importer)) {
return;
}
let resolved: string;
let resolved: string | undefined;
// Handle absolute paths
if (args.path.startsWith("/")) {
resolved = args.path;
} else if (args.path.startsWith("@/")) {
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else {
}
// Nothing matched, let other plugins handle it
else {
return;
}
// Security: prevent accessing files outside the project directory
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) {
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
if (!resolved) {
return;
}
// Vite query parameters https://vite.dev/guide/assets
@@ -114,8 +160,43 @@ async function tryFileVariants(
return basePath;
}
// If it's a directory, try index files
// If it's a directory, try package.json first, then index files
if (stat.isDirectory()) {
// Try to read package.json for entry point
try {
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
const entryExtStat = await statSafe(fs, entryWithExt);
if (entryExtStat.isFile()) {
return entryWithExt;
}
}
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
const indexStat = await statSafe(fs, indexFile);
+60 -1
View File
@@ -130,7 +130,7 @@ describe('buildProject', () => {
});
vi.mocked(mockFS.readdir)
.mockImplementation(async (path: string, _options?: { withFileTypes: true }) => {
.mockImplementation(async (path: string, _options?: { withFileTypes?: boolean }) => {
if (path === '/test/project/public') {
return [
{ name: 'favicon.ico', isDirectory: () => false, isFile: () => true },
@@ -535,4 +535,63 @@ react@^18.0.0:
// Verify tsconfig.json was attempted to be read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/tsconfig.json', 'utf8');
});
it('should support file: dependencies in package.json', async () => {
const packageJsonWithFileDeps = JSON.stringify({
name: "test-project",
dependencies: {
"@bitchat/capacitor-ble-mesh": "file:./capacitor-bitchat-mesh",
"react": "^18.2.0"
}
});
// Mock required files
vi.mocked(mockFS.readFile)
.mockImplementation(async (path: string) => {
if (path.endsWith('package.json')) {
return packageJsonWithFileDeps;
}
if (path.endsWith('index.html')) {
return '<html><head></head><body><script src="/src/main.tsx"></script></body></html>';
}
if (path.endsWith('package-lock.json')) {
return '{"dependencies": {}}';
}
throw new Error(`File not found: ${path}`);
});
// Mock stat to indicate no public directory
vi.mocked(mockFS.stat)
.mockImplementation(async (path: string) => {
if (path === '/test/project/public') {
throw new Error('Directory not found');
}
return { isDirectory: () => false, isFile: () => true };
});
// Mock additional filesystem operations for buildProject
vi.mocked(mockFS.readdir).mockImplementation(async (path: string) => {
if (path === '/test/project/dist') {
return [];
}
return [];
});
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
const result = await buildProject({
fs: mockFS,
projectPath: '/test/project',
domParser: mockDOMParser,
esmUrl: 'https://esm.shakespeare.diy',
});
// Should successfully build with file: dependencies
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
+113 -57
View File
@@ -10,6 +10,7 @@ import { fsPlugin } from "./fsPlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { Plugin } from 'esbuild-wasm';
export interface BuildProjectOptions {
fs: JSRuntimeFS;
@@ -20,6 +21,115 @@ export interface BuildProjectOptions {
esmUrl: string;
}
export interface PackageJson {
dependencies?: { [key: string]: string };
devDependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
}
export interface PackageLock {
packages: {
[key: string]: {
name?: string;
version: string;
dependencies?: { [key: string]: string };
peerDependencies?: { [key: string]: string };
} | undefined;
};
}
export interface TsConfig {
compilerOptions?: {
baseUrl?: string;
paths?: Record<string, string[]>;
};
}
export interface BuildContext {
packageJson: PackageJson;
packageLock: PackageLock;
tsconfig?: TsConfig;
}
/**
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
* Exported for use by deployment adapters that need to bundle workers
*/
export async function readBuildContext(
fs: JSRuntimeFS,
projectPath: string,
): Promise<BuildContext> {
// Read package.json
let packageJson: PackageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig: TsConfig | undefined;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock: PackageLock;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
console.log(`Building with npm (package-lock.json)`);
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
console.log(`Building with yarn (yarn.lock)`);
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
console.log(`Building with package.json only (no lock file)`);
}
}
return { packageJson, packageLock, tsconfig };
}
/**
* Create the common esbuild plugins for both project and worker builds
* Exported for use by deployment adapters that need to bundle workers
*/
export function createPlugins(
fs: JSRuntimeFS,
projectPath: string,
context: BuildContext,
esmUrl: string,
target?: string,
): Plugin[] {
return [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
];
}
async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
@@ -31,58 +141,8 @@ async function bundle(
"utf8",
);
// Read package.json
let packageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
// Try to read tsconfig.json
let tsconfig;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
// tsconfig.json is optional
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
// If package-lock.json doesn't exist, try yarn.lock
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
console.log(`Building with ${buildMode}`);
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(fs, projectPath);
const doc = domParser.parseFromString(indexHtmlText, "text/html");
const entryPoints: string[] = [];
@@ -128,11 +188,7 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
define: {
"import.meta.env": JSON.stringify({}),
},
+7 -4
View File
@@ -1,7 +1,7 @@
import type OpenAI from 'openai';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { saveFileToTmp } from './fileUtils';
import { fileToUrl } from './imageUtils';
import { fileToUrl, resizeImageIfNeeded } from './imageUtils';
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
@@ -41,8 +41,11 @@ export async function buildMessageContent(
if (attachedFiles.length > 0) {
const filePromises = attachedFiles.map(async (file) => {
try {
// Resize image if needed before processing
const processedFile = await resizeImageIfNeeded(file);
// Save file to VFS (always do this)
const savedPath = await saveFileToTmp(fs, file, tmpPath);
const savedPath = await saveFileToTmp(fs, processedFile, tmpPath);
// Always add text part with VFS path
const textPart: ContentPart = {
@@ -51,10 +54,10 @@ export async function buildMessageContent(
};
// For all image types, also add as image_url for UI display with base64 encoding
const isImage = file.type.startsWith('image/');
const isImage = processedFile.type.startsWith('image/');
if (isImage) {
try {
const imageUrl = await fileToUrl(file);
const imageUrl = await fileToUrl(processedFile);
// Return both parts: image_url for UI display and text for VFS path
return [textPart, {
type: 'image_url' as const,
+1 -1
View File
@@ -66,7 +66,7 @@ export class CurlCommand implements ShellCommand {
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
const proxiedUrl = proxyUrl({ template: this.corsProxy, url: originalUrl });
// Prepare request
const requestInit: RequestInit = {
+1 -1
View File
@@ -80,7 +80,7 @@ export class MkdirCommand implements ShellCommand {
// Create the directory
await this.fs.mkdir(absolutePath);
} else {
return createErrorResult(`${this.name}: ${dirPath}: ${error.message}`);
return createErrorResult(`${this.name}: ${dirPath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ export class TouchCommand implements ShellCommand {
await this.fs.writeFile(absolutePath, '', 'utf8');
} else {
// Other error (permission, etc.)
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
+10 -2
View File
@@ -37,6 +37,7 @@ const aiProviderSchema = z.object({
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
proxy: z.boolean().optional(),
openSecret: z.string().url().optional(),
});
const providerModelSchema = z.string().regex(
@@ -129,6 +130,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({
baseDomain: z.string().optional(),
});
const railwayProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('railway'),
apiKey: z.string(),
baseURL: z.string().optional(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
@@ -136,6 +143,7 @@ const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('ty
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
railwayProviderSchema,
]);
const deploySettingsSchema = z.object({
@@ -200,7 +208,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
};
} catch (error) {
if (error instanceof z.ZodError) {
console.error('AI settings parsing error:', error.errors);
console.error('AI settings parsing error:', error.issues);
}
return defaultSettings;
}
@@ -321,7 +329,7 @@ export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'
return deploySettingsSchema.parse(data);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Deploy settings parsing error:', error.errors);
console.error('Deploy settings parsing error:', error.issues);
}
return defaultSettings;
}
+150 -23
View File
@@ -1,6 +1,10 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
import { parse as parseJsonc } from 'jsonc-parser';
import { join } from 'path-browserify';
import { readBuildContext, createPlugins } from '../build';
import { getEsbuild } from '../esbuild';
interface AssetManifest {
[path: string]: { hash: string; size: number };
@@ -24,6 +28,16 @@ interface WorkerScript {
has_assets: boolean;
}
interface WranglerConfig {
compatibility_date?: string;
main?: string;
assets?: {
directory?: string;
html_handling?: 'auto-trailing-slash' | 'force-trailing-slash' | 'drop-trailing-slash' | 'none';
not_found_handling?: 'single-page-application' | '404-page' | 'none';
};
}
interface FileInfo {
hash: string;
content: Uint8Array;
@@ -49,6 +63,7 @@ export class CloudflareAdapter implements DeployAdapter {
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
private esmUrl: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
@@ -58,11 +73,15 @@ export class CloudflareAdapter implements DeployAdapter {
this.baseDomain = config.baseDomain || 'workers.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
this.esmUrl = config.esmUrl;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Try to read wrangler.jsonc configuration
const wranglerConfig = await this.readWranglerConfig(projectPath);
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
@@ -115,7 +134,7 @@ export class CloudflareAdapter implements DeployAdapter {
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt);
const deployment = await this.deployWorker(scriptName, completionJwt, projectPath, wranglerConfig);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
@@ -140,7 +159,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -160,7 +179,7 @@ export class CloudflareAdapter implements DeployAdapter {
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -185,7 +204,7 @@ export class CloudflareAdapter implements DeployAdapter {
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -211,7 +230,7 @@ export class CloudflareAdapter implements DeployAdapter {
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const formData = new FormData();
@@ -249,37 +268,105 @@ export class CloudflareAdapter implements DeployAdapter {
return data.result || {};
}
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
private async bundleWorker(entryPoint: string, projectPath: string): Promise<string> {
const esbuild = await getEsbuild();
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
const workerScript = `
export default {
async fetch(request, env) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
// Read build context (package.json, package-lock.json, tsconfig.json)
const context = await readBuildContext(this.fs, projectPath);
// Resolve the entry point path
const entryPointPath = entryPoint.startsWith('/')
? entryPoint
: join(projectPath, entryPoint);
// Build the worker with dependencies bundled
const results = await esbuild.build({
entryPoints: [entryPointPath],
bundle: true,
write: false,
format: "esm",
target: "esnext",
outdir: "/",
metafile: true,
sourcemap: false, // Workers typically don't need sourcemaps
plugins: createPlugins(this.fs, projectPath, context, this.esmUrl),
define: {
"import.meta.env": JSON.stringify({}),
},
});
if (results.outputFiles.length === 0) {
throw new Error(`Failed to bundle worker: no output files generated`);
}
// Return the bundled worker code as a string
return results.outputFiles[0].text;
}
};
`;
private async deployWorker(
scriptName: string,
assetsJwt: string,
projectPath: string,
wranglerConfig?: WranglerConfig
): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Determine the main module name from wrangler.jsonc or try defaults
let mainModuleName = 'worker.js';
let workerScript = this.getDefaultWorkerScript();
if (wranglerConfig?.main) {
// Use explicitly configured main module
const configuredModule = wranglerConfig.main;
try {
const workerExists = await this.fileExists(join(projectPath, configuredModule));
if (workerExists) {
mainModuleName = configuredModule;
workerScript = await this.bundleWorker(configuredModule, projectPath);
} else {
throw new Error(`Configured worker file not found: ${configuredModule}`);
}
} catch (error) {
console.warn(`Failed to bundle configured worker script, using default:`, error);
// Keep default values
}
} else {
// Try default worker files in order: worker.ts -> worker.mjs -> worker.js
const defaultWorkerFiles = ['worker.ts', 'worker.mjs', 'worker.js'];
for (const filename of defaultWorkerFiles) {
try {
const workerExists = await this.fileExists(join(projectPath, filename));
if (workerExists) {
mainModuleName = filename;
workerScript = await this.bundleWorker(filename, projectPath);
break; // Successfully bundled, stop searching
}
} catch (error) {
console.warn(`Failed to bundle ${filename}:`, error);
// Continue to next file
}
}
// If no custom worker found, use default values already set
}
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append('worker.js', scriptBlob, 'worker.js');
formData.append(mainModuleName, scriptBlob, mainModuleName);
// Add metadata with assets configuration
const metadata = {
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
main_module: mainModuleName,
compatibility_date: wranglerConfig?.compatibility_date || new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
html_handling: wranglerConfig?.assets?.html_handling || 'auto-trailing-slash',
not_found_handling: wranglerConfig?.assets?.not_found_handling || 'single-page-application',
},
},
};
@@ -303,6 +390,27 @@ export default {
return data.result;
}
private async readWranglerConfig(projectPath: string): Promise<WranglerConfig | undefined> {
// Try wrangler.jsonc first, then wrangler.json
const configPaths = [
join(projectPath, 'wrangler.jsonc'),
join(projectPath, 'wrangler.json'),
];
for (const configPath of configPaths) {
try {
const configContent = await this.fs.readFile(configPath, 'utf8');
// Parse JSONC (JSON with comments) using jsonc-parser
return parseJsonc(configContent) as WranglerConfig;
} catch {
// Continue to next path
}
}
// No wrangler config found, return undefined
return undefined;
}
private async collectFiles(
dirPath: string,
relativePath: string,
@@ -403,4 +511,23 @@ export default {
};
return mimeTypes[ext] || 'application/octet-stream';
}
private async fileExists(path: string): Promise<boolean> {
try {
const stat = await this.fs.stat(path);
return stat.isFile();
} catch {
return false;
}
}
private getDefaultWorkerScript(): string {
return `export default {
async fetch(request) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
}
};`;
}
}
+3 -3
View File
@@ -96,7 +96,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -116,7 +116,7 @@ export class DenoDeployAdapter implements DeployAdapter {
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -143,7 +143,7 @@ export class DenoDeployAdapter implements DeployAdapter {
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
+198 -29
View File
@@ -11,11 +11,13 @@ interface NetlifySite {
admin_url: string;
}
interface NetlifyBuildResponse {
interface NetlifyDeployResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
required?: string[];
required_functions?: string[];
}
/**
@@ -65,31 +67,47 @@ export class NetlifyAdapter implements DeployAdapter {
siteUrl = site.url;
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Collect files and their SHA1 hashes
const files: Record<string, string> = {};
const fileContents = new Map<string, Uint8Array>();
await this.collectFiles(distPath, '', files, fileContents);
// Ensure _redirects file exists for SPA routing
await this.ensureRedirectsFile(distPath, zip);
await this.ensureRedirectsInFiles(distPath, files, fileContents);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Collect functions and their SHA256 hashes
const functions: Record<string, string> = {};
const functionZips = new Map<string, Blob>();
const functionsPath = `${projectPath}/netlify/functions`;
await this.collectFunctions(functionsPath, functions, functionZips);
// Deploy to Netlify
await this.triggerDeploy(activeSiteId, zipBlob);
// Create deploy with file and function digests
const deployResponse = await this.createDeployWithDigest(activeSiteId, files, functions);
// Upload required files
if (deployResponse.required && deployResponse.required.length > 0) {
await this.uploadFiles(deployResponse.id, files, fileContents, deployResponse.required);
}
// Upload required functions
if (deployResponse.required_functions && deployResponse.required_functions.length > 0) {
await this.uploadFunctions(deployResponse.id, functions, functionZips, deployResponse.required_functions);
}
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
deployId: deployResponse.id,
provider: 'netlify',
functionsDeployed: Object.keys(functions).length,
},
};
}
private async createSite(name: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
@@ -113,7 +131,7 @@ export class NetlifyAdapter implements DeployAdapter {
private async getSite(siteId: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites/${siteId}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'GET',
@@ -130,45 +148,57 @@ export class NetlifyAdapter implements DeployAdapter {
return response.json();
}
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
private async createDeployWithDigest(
siteId: string,
files: Record<string, string>,
functions: Record<string, string>
): Promise<NetlifyDeployResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const body: { files: Record<string, string>; functions?: Record<string, string> } = { files };
if (Object.keys(functions).length > 0) {
body.functions = functions;
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/zip',
'Content-Type': 'application/json',
},
body: zipBlob,
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
throw new Error(`Failed to create Netlify deploy: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
private async collectFiles(
dirPath: string,
relativePath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
await this.collectFiles(fullPath, relPath, files, fileContents);
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
const sha1 = await this.calculateSHA1(fileContent);
files[`/${relPath}`] = sha1;
fileContents.set(sha1, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
@@ -181,9 +211,13 @@ export class NetlifyAdapter implements DeployAdapter {
/**
* Ensures _redirects file exists in the deployment for SPA routing
* If not present in dist directory, adds it to the ZIP with default content
* If not present in dist directory, adds it to the files manifest
*/
private async ensureRedirectsFile(distPath: string, zip: JSZip): Promise<void> {
private async ensureRedirectsInFiles(
distPath: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>
): Promise<void> {
const redirectsPath = `${distPath}/_redirects`;
try {
@@ -192,11 +226,146 @@ export class NetlifyAdapter implements DeployAdapter {
if (!stat.isFile()) {
throw new Error('_redirects is not a file');
}
// File exists, no need to add it (already added by addDirectoryToZip)
// File exists, already collected by collectFiles
} catch {
// File doesn't exist, add default _redirects to ZIP
// File doesn't exist, add default _redirects
const defaultRedirects = '/* /index.html 200';
zip.file('_redirects', defaultRedirects);
const content = new TextEncoder().encode(defaultRedirects);
const sha1 = await this.calculateSHA1(content);
files['/_redirects'] = sha1;
fileContents.set(sha1, content);
}
}
private async collectFunctions(
functionsPath: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>
): Promise<void> {
try {
// Check if functions directory exists
const stat = await this.fs.stat(functionsPath);
if (!stat.isDirectory()) {
return;
}
const entries = await this.fs.readdir(functionsPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile()) {
const fullPath = `${functionsPath}/${entry.name}`;
// Only process .mjs files (ES modules)
// Note: .js and .ts files require bundling which is not supported in this adapter
if (entry.name.endsWith('.mjs')) {
try {
const functionContent = await this.fs.readFile(fullPath);
// Create a zip for this function
const zip = new JSZip();
zip.file(entry.name, functionContent);
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Calculate SHA256 hash
const sha256 = await this.calculateSHA256FromBlob(zipBlob);
// Function name without extension
const functionName = entry.name.replace(/\.mjs$/, '');
functions[functionName] = sha256;
functionZips.set(sha256, zipBlob);
} catch (error) {
console.warn(`Failed to process function ${entry.name}:`, error);
}
}
}
}
} catch {
// Functions directory doesn't exist, skip
}
}
private async uploadFiles(
deployId: string,
files: Record<string, string>,
fileContents: Map<string, Uint8Array>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [filePath, sha1] of Object.entries(files)) {
if (requiredSet.has(sha1)) {
const content = fileContents.get(sha1);
if (!content) {
console.warn(`Content not found for ${filePath} (${sha1})`);
continue;
}
// Escape file path for URL
const encodedPath = filePath.split('/').map(encodeURIComponent).join('/');
const url = `${this.baseURL}/deploys/${deployId}/files${encodedPath}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: content,
});
if (!response.ok) {
console.warn(`Failed to upload file ${filePath}: ${response.status} ${response.statusText}`);
}
}
}
}
private async uploadFunctions(
deployId: string,
functions: Record<string, string>,
functionZips: Map<string, Blob>,
requiredShas: string[]
): Promise<void> {
const requiredSet = new Set(requiredShas);
for (const [functionName, sha256] of Object.entries(functions)) {
if (requiredSet.has(sha256)) {
const zipBlob = functionZips.get(sha256);
if (!zipBlob) {
console.warn(`Zip not found for function ${functionName} (${sha256})`);
continue;
}
const url = `${this.baseURL}/deploys/${deployId}/functions/${encodeURIComponent(functionName)}?runtime=js`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/octet-stream',
},
body: zipBlob,
});
if (!response.ok) {
console.warn(`Failed to upload function ${functionName}: ${response.status} ${response.statusText}`);
}
}
}
}
private async calculateSHA1(data: Uint8Array): Promise<string> {
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
private async calculateSHA256FromBlob(blob: Blob): Promise<string> {
const arrayBuffer = await blob.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
}
}
+627
View File
@@ -0,0 +1,627 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, RailwayDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface Workspace {
id: string;
name: string;
team: {
id: string;
} | null;
projects: {
edges: Array<{
node: Project;
}>;
};
}
interface Project {
id: string;
name: string;
environments: {
edges: Array<{
node: Environment;
}>;
};
services: {
edges: Array<{
node: Service;
}>;
};
}
interface Environment {
id: string;
name: string;
}
interface Service {
id: string;
name: string;
}
interface DeploymentResponse {
deploymentId: string;
url: string;
logsUrl?: string;
deploymentDomain: string;
}
/**
* Railway Deploy Adapter
* Uses Railway GraphQL API and REST upload endpoint
*
* Implements the Railway deployment workflow:
* 1. Query for workspaces and projects (or use provided IDs)
* 2. Create project if needed
* 3. Create service if needed
* 4. Create tarball of entire source code (excluding common dev files)
* 5. Upload tarball to Railway via multipart/form-data
*/
export class RailwayAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string;
private workspaceId?: string;
private projectId?: string;
private environmentId?: string;
private serviceId?: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: RailwayDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://backboard.railway.com';
this.workspaceId = config.workspaceId;
this.projectId = config.projectId;
this.environmentId = config.environmentId;
this.serviceId = config.serviceId;
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Step 1: Ensure we have a workspace
if (!this.workspaceId) {
const workspaces = await this.getWorkspaces();
if (workspaces.length === 0) {
throw new Error('No workspaces found. Please create a workspace on Railway first.');
}
this.workspaceId = workspaces[0].id;
}
// Step 2: Get or create project
let activeProjectId = this.projectId;
let activeEnvironmentId = this.environmentId;
if (!activeProjectId) {
const project = await this.createProject(this.projectName || projectId);
activeProjectId = project.id;
// Get the default production environment
activeEnvironmentId = project.environments.edges[0]?.node.id;
} else if (!activeEnvironmentId) {
// If we have project ID but no environment, fetch the project to get the environment
const project = await this.getProject(activeProjectId);
activeEnvironmentId = project.environments.edges[0]?.node.id;
}
if (!activeEnvironmentId) {
throw new Error('No environment found for project');
}
// Step 3: Get or create service
let activeServiceId = this.serviceId;
if (!activeServiceId) {
const service = await this.createService(activeProjectId, projectId);
activeServiceId = service.id;
}
// Step 4: Create tarball of source code
const tarball = await this.createTarball(projectPath);
// Step 5: Upload to Railway
const deployment = await this.uploadDeployment(
activeProjectId,
activeEnvironmentId,
activeServiceId,
tarball
);
// Step 6: Wait for deployment to complete
await this.waitForDeployment(deployment.deploymentId);
// Step 7: Check for existing domains and create one if needed
const domain = await this.ensureServiceDomain(
activeProjectId,
activeEnvironmentId,
activeServiceId
);
return {
url: domain ? `https://${domain}` : deployment.url,
metadata: {
deploymentId: deployment.deploymentId,
projectId: activeProjectId,
environmentId: activeEnvironmentId,
serviceId: activeServiceId,
provider: 'railway',
deploymentDomain: domain || deployment.deploymentDomain,
},
};
}
private async graphqlRequest<T>(query: string, variables?: Record<string, unknown>): Promise<T> {
const url = `${this.baseURL}/graphql/v2`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Railway GraphQL request failed: ${response.status} ${response.statusText}. ${errorText}`);
}
const result = await response.json();
if (result.errors) {
const errorMessages = result.errors.map((e: { message: string }) => e.message).join(', ');
throw new Error(`Railway GraphQL error: ${errorMessages}`);
}
return result.data;
}
private async getWorkspaces(): Promise<Workspace[]> {
const query = `
query UserWorkspaces {
me {
workspaces {
id
name
team {
id
}
projects(first: 500) {
edges {
node {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ me: { workspaces: Workspace[] } }>(query);
return data.me.workspaces;
}
private async getProject(projectId: string): Promise<Project> {
const query = `
query GetProject($projectId: String!) {
project(id: $projectId) {
id
name
environments {
edges {
node {
id
name
}
}
}
services {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ project: Project }>(query, { projectId });
return data.project;
}
private async createProject(name: string): Promise<Project> {
const query = `
mutation ProjectCreate($name: String, $workspaceId: String) {
projectCreate(input: {
name: $name,
workspaceId: $workspaceId
}) {
id
name
environments {
edges {
node {
id
name
}
}
}
}
}
`;
const data = await this.graphqlRequest<{ projectCreate: Project }>(query, {
name,
workspaceId: this.workspaceId,
});
return data.projectCreate;
}
private async createService(projectId: string, name: string): Promise<Service> {
const query = `
mutation ServiceCreate($input: ServiceCreateInput!) {
serviceCreate(input: $input) {
id
name
}
}
`;
const data = await this.graphqlRequest<{ serviceCreate: Service }>(query, {
input: {
name,
projectId,
source: {
image: null,
repo: null,
},
},
});
return data.serviceCreate;
}
private async createTarball(projectPath: string): Promise<Blob> {
// Import tar library dynamically (needs to be available in the project)
// For browser environment, we'll need to use a tar implementation
// Using a simpler approach: collect files and create a tar-like structure
// Collect all files excluding common dev files
const files = new Map<string, Uint8Array>();
await this.collectFilesForTarball(projectPath, '', files);
// Create a simple tar.gz equivalent using browser APIs
// Since we're in a browser environment, we'll create a structure that Railway can accept
const tarData = await this.createTarGzBlob(files);
return tarData;
}
private async collectFilesForTarball(
dirPath: string,
relativePath: string,
files: Map<string, Uint8Array>
): Promise<void> {
// Directories to exclude
const excludeDirs = new Set([
'.git',
'node_modules',
'dist',
'build',
'.next',
'.nuxt',
'.output',
'.vite',
'.cache',
'__pycache__',
'.pytest_cache',
'.venv',
'venv',
'env',
'.DS_Store',
'coverage',
'.nyc_output',
]);
// Files to exclude
const excludeFiles = new Set([
'.env',
'.env.local',
'.env.development',
'.env.production',
'.env.test',
'npm-debug.log',
'yarn-debug.log',
'yarn-error.log',
'.DS_Store',
]);
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
// Skip excluded directories and files
if (excludeDirs.has(entry.name) || excludeFiles.has(entry.name)) {
continue;
}
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFilesForTarball(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
let bytes: Uint8Array;
if (typeof fileContent === 'string') {
bytes = new TextEncoder().encode(fileContent);
} else {
bytes = fileContent;
}
files.set(entryRelativePath, bytes);
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private async createTarGzBlob(files: Map<string, Uint8Array>): Promise<Blob> {
// Create a simple tar structure
// TAR format: 512-byte header + file data (padded to 512 bytes)
const blocks: Uint8Array[] = [];
for (const [filePath, content] of files) {
// Create tar header (simplified)
const header = new Uint8Array(512);
const encoder = new TextEncoder();
// File name (offset 0, 100 bytes)
const nameBytes = encoder.encode(filePath);
header.set(nameBytes.slice(0, 100), 0);
// File mode (offset 100, 8 bytes) - "0000644\0"
header.set(encoder.encode('0000644\0'), 100);
// Owner UID (offset 108, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 108);
// Group GID (offset 116, 8 bytes) - "0000000\0"
header.set(encoder.encode('0000000\0'), 116);
// File size in octal (offset 124, 12 bytes)
const sizeOctal = content.length.toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(sizeOctal), 124);
// Modification time (offset 136, 12 bytes)
const mtime = Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0';
header.set(encoder.encode(mtime), 136);
// Checksum (offset 148, 8 bytes) - calculate after setting type flag
header.set(encoder.encode(' '), 148);
// Type flag (offset 156, 1 byte) - '0' for regular file
header.set(encoder.encode('0'), 156);
// Calculate checksum
let checksum = 0;
for (let i = 0; i < 512; i++) {
checksum += header[i];
}
const checksumOctal = checksum.toString(8).padStart(6, '0') + '\0 ';
header.set(encoder.encode(checksumOctal), 148);
blocks.push(header);
// Add file content, padded to 512-byte boundary
const paddedSize = Math.ceil(content.length / 512) * 512;
const paddedContent = new Uint8Array(paddedSize);
paddedContent.set(content);
blocks.push(paddedContent);
}
// Add two empty 512-byte blocks to mark end of archive
blocks.push(new Uint8Array(512));
blocks.push(new Uint8Array(512));
// Combine all blocks
const totalSize = blocks.reduce((sum, block) => sum + block.length, 0);
const tarData = new Uint8Array(totalSize);
let offset = 0;
for (const block of blocks) {
tarData.set(block, offset);
offset += block.length;
}
// Compress with gzip (using CompressionStream API)
const stream = new Blob([tarData]).stream();
const compressedStream = stream.pipeThrough(new CompressionStream('gzip'));
const compressedBlob = await new Response(compressedStream).blob();
return compressedBlob;
}
private async uploadDeployment(
projectId: string,
environmentId: string,
serviceId: string,
tarball: Blob
): Promise<DeploymentResponse> {
const url = `${this.baseURL}/project/${projectId}/environment/${environmentId}/up?serviceId=${serviceId}`;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url;
// Railway expects the raw tarball bytes with Content-Type: multipart/form-data
// NOT wrapped in FormData
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'multipart/form-data',
},
body: tarball,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to upload deployment to Railway: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async ensureServiceDomain(
projectId: string,
environmentId: string,
serviceId: string
): Promise<string | null> {
try {
// First, check if a domain already exists
const domainsQuery = `
query Domains($environmentId: String!, $projectId: String!, $serviceId: String!) {
domains(environmentId: $environmentId, projectId: $projectId, serviceId: $serviceId) {
serviceDomains {
id
domain
}
customDomains {
id
domain
}
}
}
`;
const domainsResult = await this.graphqlRequest<{
domains: {
serviceDomains: Array<{ id: string; domain: string }>;
customDomains: Array<{ id: string; domain: string }>;
};
}>(domainsQuery, {
environmentId,
projectId,
serviceId,
});
// If a domain already exists, return it
if (domainsResult.domains.serviceDomains.length > 0) {
return domainsResult.domains.serviceDomains[0].domain;
}
if (domainsResult.domains.customDomains.length > 0) {
return domainsResult.domains.customDomains[0].domain;
}
// No domain exists, create a Railway-provided domain
const createDomainMutation = `
mutation ServiceDomainCreate($environmentId: String!, $serviceId: String!) {
serviceDomainCreate(input: { environmentId: $environmentId, serviceId: $serviceId }) {
id
domain
}
}
`;
const createResult = await this.graphqlRequest<{
serviceDomainCreate: {
id: string;
domain: string;
};
}>(createDomainMutation, {
environmentId,
serviceId,
});
return createResult.serviceDomainCreate.domain;
} catch (error) {
console.warn('Failed to create/get service domain:', error);
// Return null to fall back to the dashboard URL
return null;
}
}
private async waitForDeployment(deploymentId: string): Promise<void> {
const query = `
query Deployment($id: String!) {
deployment(id: $id) {
id
status
}
}
`;
const maxAttempts = 180; // 15 minutes max (5 second intervals)
let attempts = 0;
while (attempts < maxAttempts) {
attempts++;
try {
const result = await this.graphqlRequest<{
deployment: {
id: string;
status: string;
};
}>(query, { id: deploymentId });
const status = result.deployment.status;
if (status === 'SUCCESS') {
return; // Deployment successful
}
if (status === 'FAILED') {
throw new Error('Deployment failed. Check the Railway dashboard for build logs.');
}
if (status === 'CRASHED') {
throw new Error('Deployment crashed. Check the Railway dashboard for logs.');
}
// Status is BUILDING, DEPLOYING, or other in-progress state
// Wait 5 seconds before checking again
await new Promise(resolve => setTimeout(resolve, 5000));
} catch (error) {
// If it's our thrown error, re-throw it
if (error instanceof Error && (error.message.includes('failed') || error.message.includes('crashed'))) {
throw error;
}
// Otherwise, wait and retry
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
throw new Error('Deployment timed out after 15 minutes. Check the Railway dashboard for status.');
}
}
+1 -1
View File
@@ -72,7 +72,7 @@ export class ShakespeareAdapter implements DeployAdapter {
// Apply proxy if configured
if (this.corsProxy) {
request = new Request(proxyUrl(this.corsProxy, request.url), request);
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
}
// Deploy
+1 -1
View File
@@ -68,7 +68,7 @@ export class VercelAdapter implements DeployAdapter {
}
// Apply proxy if configured
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: apiUrl }) : apiUrl;
// Deploy to Vercel
const response = await fetch(targetUrl, {
+1
View File
@@ -5,3 +5,4 @@ export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
export * from './RailwayAdapter';
+14 -1
View File
@@ -63,6 +63,7 @@ export interface CloudflareDeployConfig {
baseDomain?: string;
projectName?: string;
corsProxy?: string;
esmUrl: string;
}
export interface DenoDeployConfig {
@@ -75,9 +76,21 @@ export interface DenoDeployConfig {
corsProxy?: string;
}
export interface RailwayDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
baseURL?: string;
workspaceId?: string;
projectId?: string;
environmentId?: string;
serviceId?: string;
projectName?: string;
corsProxy?: string;
}
export interface PresetDeployProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno';
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
name: string;
description: string;
baseURL?: string;
+10
View File
@@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
organizationIdURL: 'https://dash.deno.com/orgs',
proxy: true,
},
{
id: 'railway',
type: 'railway',
name: 'Railway',
description: 'Deploy to Railway',
baseURL: 'https://backboard.railway.com',
apiKeyLabel: 'API Token',
apiKeyURL: 'https://railway.app/account/tokens',
proxy: true,
},
];
+11 -5
View File
@@ -1,15 +1,21 @@
import UriTemplate from 'uri-templates';
export interface FaviconUrlOpts {
template: string;
url: string | URL;
}
/**
* Generate a favicon URL from a template and input URL
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
* @param url - The URL to extract parts from
* @param opts - Options object
* @param opts.template - URL template with placeholders like {hostname}, {origin}, etc.
* @param opts.url - The URL to extract parts from
* @returns The hydrated favicon URL
*/
export function faviconUrl(template: string, url: string | URL): string {
const u = new URL(url);
export function faviconUrl(opts: FaviconUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+1 -2
View File
@@ -1107,7 +1107,6 @@ class GitHttp implements HttpClient {
constructor(proxy?: string, fetch?: typeof globalThis.fetch) {
this.proxy = proxy;
// Bind fetch to globalThis to preserve context when called as this.fetch()
this.fetch = fetch ?? globalThis.fetch.bind(globalThis);
}
@@ -1116,7 +1115,7 @@ class GitHttp implements HttpClient {
const url = new URL(request.url);
const target = this.proxy
? proxyUrl(this.proxy, url)
? proxyUrl({ template: this.proxy, url })
: url.href;
const init: RequestInit = {
+140
View File
@@ -1,3 +1,143 @@
export interface ResizeOptions {
/** Maximum width or height in pixels (default: 2048) */
maxDimension?: number;
/** Maximum file size in bytes (default: 5MB) */
maxFileSize?: number;
/** JPEG quality 0-1 (default: 0.92) */
quality?: number;
}
/**
* Resizes an image file if it exceeds size or dimension limits.
*
* @param file - The image file to potentially resize
* @param opts - Resize options with defaults
* @returns Promise resolving to the original or resized File
*/
export async function resizeImageIfNeeded(file: File, opts: ResizeOptions = {}): Promise<File> {
const {
maxDimension = 2048,
maxFileSize = 5 * 1024 * 1024, // 5MB
quality = 0.92,
} = opts;
// Only process image files
if (!file.type.startsWith('image/')) {
return file;
}
// Check if resize is needed based on file size
const needsResize = file.size > maxFileSize;
if (!needsResize) {
// Still need to check dimensions
const dimensions = await getImageDimensions(file);
if (dimensions.width <= maxDimension && dimensions.height <= maxDimension) {
return file;
}
}
// Resize the image
return await resizeImage(file, maxDimension, quality);
}
/**
* Gets the dimensions of an image file.
*
* @param file - The image file
* @returns Promise resolving to width and height
*/
async function getImageDimensions(file: File): Promise<{ width: number; height: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
resolve({ width: img.width, height: img.height });
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image'));
};
img.src = url;
});
}
/**
* Resizes an image to fit within maxDimension while maintaining aspect ratio.
*
* @param file - The image file to resize
* @param maxDimension - Maximum width or height
* @param quality - JPEG quality 0-1
* @returns Promise resolving to resized File
*/
async function resizeImage(file: File, maxDimension: number, quality: number): Promise<File> {
return new Promise((resolve, reject) => {
const img = new Image();
const url = URL.createObjectURL(file);
img.onload = () => {
URL.revokeObjectURL(url);
// Calculate new dimensions maintaining aspect ratio
let { width, height } = img;
if (width > maxDimension || height > maxDimension) {
if (width > height) {
height = (height / width) * maxDimension;
width = maxDimension;
} else {
width = (width / height) * maxDimension;
height = maxDimension;
}
}
// Create canvas and draw resized image
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('Failed to get canvas context'));
return;
}
ctx.drawImage(img, 0, 0, width, height);
// Convert canvas to blob
canvas.toBlob(
(blob) => {
if (!blob) {
reject(new Error('Failed to create blob from canvas'));
return;
}
// Create new File from blob with original name
const resizedFile = new File([blob], file.name, {
type: file.type || 'image/jpeg',
lastModified: Date.now(),
});
resolve(resizedFile);
},
file.type || 'image/jpeg',
quality
);
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load image for resizing'));
};
img.src = url;
});
}
/**
* Converts a File to a base64-encoded data URL for API consumption.
*
+6 -6
View File
@@ -9,7 +9,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
});
@@ -20,7 +20,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1/);
});
@@ -31,7 +31,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe(`https://example.com/${pubkey}`);
});
@@ -42,7 +42,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toBe('https://example.com/my-repo');
});
@@ -53,7 +53,7 @@ describe('ngitWebUrl', () => {
const identifier = 'my-repo';
const nostrURI = new NostrURI({ pubkey, identifier });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
expect(result).toMatch(/^https:\/\/example\.com\/npub1[^/]+\/my-repo$/);
});
@@ -65,7 +65,7 @@ describe('ngitWebUrl', () => {
const relay = 'wss://relay.example.com/';
const nostrURI = new NostrURI({ pubkey, identifier, relay });
const result = ngitWebUrl(template, nostrURI);
const result = ngitWebUrl({ template, nostrURI });
// The naddr should be longer when it includes relay information
expect(result).toMatch(/^https:\/\/nostrhub\.io\/naddr1/);
+14 -8
View File
@@ -2,20 +2,26 @@ import UriTemplate from 'uri-templates';
import { nip19 } from 'nostr-tools';
import { NostrURI } from './NostrURI';
export interface NgitWebUrlOpts {
template: string;
nostrURI: NostrURI;
}
/**
* Generate a Nostr Git web URL from a template and Nostr URI
* @param template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @param opts - Options object
* @param opts.template - URL template with placeholders like {naddr}, {npub}, {pubkey}, {identifier}
* @param opts.nostrURI - The Nostr URI containing pubkey, identifier, and optional relay
* @returns The hydrated web URL
*/
export function ngitWebUrl(template: string, nostrURI: NostrURI): string {
const naddr = nostrURI.toNaddr();
const npub = nip19.npubEncode(nostrURI.pubkey);
export function ngitWebUrl(opts: NgitWebUrlOpts): string {
const naddr = opts.nostrURI.toNaddr();
const npub = nip19.npubEncode(opts.nostrURI.pubkey);
return UriTemplate(template).fill({
return UriTemplate(opts.template).fill({
naddr,
npub,
pubkey: nostrURI.pubkey,
identifier: nostrURI.identifier,
pubkey: opts.nostrURI.pubkey,
identifier: opts.nostrURI.identifier,
});
}
+1 -386
View File
@@ -1,14 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './plugins';
import { getPlugins } from './plugins';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
@@ -164,24 +156,6 @@ describe('plugins', () => {
fs = new MockFS();
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names with hyphens', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
expect(isValidSkillName('test-name')).toBe(true);
expect(isValidSkillName('test-123')).toBe(true);
expect(isValidSkillName('condition-based-waiting')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('Test-Name')).toBe(false);
});
});
describe('getPlugins', () => {
it('should return empty array when plugins directory does not exist', async () => {
const plugins = await getPlugins(fs, '/plugins');
@@ -199,363 +173,4 @@ describe('plugins', () => {
expect(plugins).not.toContain('file.txt');
});
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
});
});
-169
View File
@@ -1,38 +1,13 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
import * as git from 'isomorphic-git';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
export interface PluginGitInfo {
commitHash: string;
commitDate: Date;
commitMessage: string;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get all plugins from the plugins directory
*/
@@ -55,150 +30,6 @@ export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<
}
}
/**
* Get all skills from a single plugin
*/
function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a project's skills directory
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(projectPath, 'skills'), 'project');
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
/**
* Get git information for a plugin
*/
+8 -3
View File
@@ -1,8 +1,13 @@
import UriTemplate from 'uri-templates';
export function proxyUrl(template: string, url: string | URL): string {
const u = new URL(url);
return UriTemplate(template).fill({
export interface ProxyUrlOpts {
template: string;
url: string | URL;
}
export function proxyUrl(opts: ProxyUrlOpts): string {
const u = new URL(opts.url);
return UriTemplate(opts.template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
+1 -7
View File
@@ -1,4 +1,4 @@
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Wallet } from 'lucide-react';
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
export interface SettingsItem {
id: string;
@@ -59,12 +59,6 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
title: t('nostrSettings'),
href: '/settings/nostr',
},
{
id: 'wallet',
icon: Wallet,
title: t('walletSettings'),
href: '/settings/wallet',
},
],
},
{
+705
View File
@@ -0,0 +1,705 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type { JSRuntimeFS } from './JSRuntime';
import {
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './skills';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string | Uint8Array> = new Map();
private dirs: Set<string> = new Set();
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (!content) throw new Error(`ENOENT: ${path}`);
const encoding = typeof options === 'string' ? options : options?.encoding;
if (encoding === 'utf8') {
return typeof content === 'string' ? content : new TextDecoder().decode(content);
}
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
}
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
this.files.set(path, data);
// Auto-create parent directories
const parts = path.split('/');
for (let i = 1; i < parts.length; i++) {
this.dirs.add(parts.slice(0, i).join('/') || '/');
}
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]> {
if (!this.dirs.has(path)) throw new Error(`ENOENT: ${path}`);
const entries = new Set<string>();
const prefix = path === '/' ? '/' : path + '/';
// Check files
for (const filePath of this.files.keys()) {
if (filePath.startsWith(prefix)) {
const relativePath = filePath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
// Check directories
for (const dirPath of this.dirs) {
if (dirPath.startsWith(prefix) && dirPath !== path) {
const relativePath = dirPath.slice(prefix.length);
const firstPart = relativePath.split('/')[0];
if (firstPart) entries.add(firstPart);
}
}
const names = Array.from(entries);
if (options?.withFileTypes) {
return names.map(name => {
const fullPath = path === '/' ? `/${name}` : `${path}/${name}`;
const isDir = this.dirs.has(fullPath);
return {
name,
isDirectory: () => isDir,
isFile: () => !isDir,
};
});
}
return names;
}
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
if (options?.recursive) {
const parts = path.split('/');
for (let i = 1; i <= parts.length; i++) {
const dir = parts.slice(0, i).join('/') || '/';
this.dirs.add(dir);
}
} else {
this.dirs.add(path);
}
}
async stat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
const isDir = this.dirs.has(path);
const isFile = this.files.has(path);
if (!isDir && !isFile) throw new Error(`ENOENT: ${path}`);
return {
isDirectory: () => isDir,
isFile: () => isFile,
};
}
async rm(path: string, options?: { recursive?: boolean }): Promise<void> {
this.files.delete(path);
this.dirs.delete(path);
if (options?.recursive) {
const prefix = path + '/';
for (const filePath of Array.from(this.files.keys())) {
if (filePath.startsWith(prefix)) {
this.files.delete(filePath);
}
}
for (const dirPath of Array.from(this.dirs)) {
if (dirPath.startsWith(prefix)) {
this.dirs.delete(dirPath);
}
}
}
}
async rmdir(path: string, options?: { recursive?: boolean }): Promise<void> {
return this.rm(path, options);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
const content = this.files.get(oldPath);
if (content) {
this.files.set(newPath, content);
this.files.delete(oldPath);
}
}
async lstat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
return this.stat(path);
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in MockFS');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in MockFS');
}
}
describe('skills', () => {
let fs: MockFS;
beforeEach(() => {
fs = new MockFS();
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names with hyphens', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
expect(isValidSkillName('test-name')).toBe(true);
expect(isValidSkillName('test-123')).toBe(true);
expect(isValidSkillName('condition-based-waiting')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('Test-Name')).toBe(false);
});
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
it('should check .agents/skills first', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
it('should check .opencode/skills second', async () => {
const projectPath = '/projects/myproject';
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .opencode/skills
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('opencode-skill');
expect(skills[0].description).toBe('Skill from .opencode/skills');
});
it('should check .claude/skills third', async () => {
const projectPath = '/projects/myproject';
const claudeSkillPath = `${projectPath}/.claude/skills/claude-skill`;
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in .claude/skills
await fs.mkdir(claudeSkillPath, { recursive: true });
await fs.writeFile(
`${claudeSkillPath}/SKILL.md`,
`---
name: claude-skill
description: Skill from .claude/skills
---
Content`
);
// Create skill in skills directory (should be ignored)
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('claude-skill');
expect(skills[0].description).toBe('Skill from .claude/skills');
});
it('should fall back to skills directory if no other directories exist', async () => {
const projectPath = '/projects/myproject';
const regularSkillPath = `${projectPath}/skills/regular-skill`;
// Create skill in skills directory only
await fs.mkdir(regularSkillPath, { recursive: true });
await fs.writeFile(
`${regularSkillPath}/SKILL.md`,
`---
name: regular-skill
description: Skill from skills directory
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('regular-skill');
expect(skills[0].description).toBe('Skill from skills directory');
});
it('should prioritize .agents/skills over .opencode/skills', async () => {
const projectPath = '/projects/myproject';
const agentsSkillPath = `${projectPath}/.agents/skills/agent-skill`;
const opencodeSkillPath = `${projectPath}/.opencode/skills/opencode-skill`;
// Create skill in .agents/skills
await fs.mkdir(agentsSkillPath, { recursive: true });
await fs.writeFile(
`${agentsSkillPath}/SKILL.md`,
`---
name: agent-skill
description: Skill from .agents/skills
---
Content`
);
// Create skill in .opencode/skills (should be ignored)
await fs.mkdir(opencodeSkillPath, { recursive: true });
await fs.writeFile(
`${opencodeSkillPath}/SKILL.md`,
`---
name: opencode-skill
description: Skill from .opencode/skills
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('agent-skill');
expect(skills[0].description).toBe('Skill from .agents/skills');
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
});
+194
View File
@@ -0,0 +1,194 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
/**
* Validates a skill name (alphanumeric lowercase with hyphens)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9-]+$/.test(name);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be lowercase alphanumeric with hyphens)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist
return [];
}
return skills;
}
/**
* Get all skills from a single plugin
*/
export function getSkillsFromPlugin(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get all skills from a project's skills directory
* Checks for skills in order: .agents/skills, .opencode/skills, .claude/skills, skills
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
const skillsPaths = [
join(projectPath, '.agents', 'skills'),
join(projectPath, '.opencode', 'skills'),
join(projectPath, '.claude', 'skills'),
join(projectPath, 'skills'),
];
// Try each path in order and return skills from the first one that exists
for (const skillsPath of skillsPaths) {
try {
const stat = await fs.stat(skillsPath);
if (stat.isDirectory()) {
return getSkillsFromDirectory(fs, skillsPath, 'project');
}
} catch {
// Directory doesn't exist, try next one
continue;
}
}
// No skills directory found
return [];
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const { getPlugins } = await import('./plugins');
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
+28 -26
View File
@@ -6,8 +6,8 @@ import { NostrMetadata } from '@nostrify/nostrify';
import { AppConfig } from '@/contexts/AppContext';
import OpenAI from 'openai';
// Mock the plugins module
vi.mock('./plugins', () => ({
// Mock the skills module
vi.mock('./skills', () => ({
getAllSkills: vi.fn(),
}));
@@ -16,7 +16,7 @@ vi.mock('path-browserify', () => ({
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
}));
import { getAllSkills } from './plugins';
import { getAllSkills } from './skills';
// Test configuration
const testConfig: AppConfig = {
@@ -196,14 +196,14 @@ describe('makeSystemPrompt', () => {
});
describe('tools section', () => {
it('should show no tools message when no tools are provided', async () => {
it('should pass tools to template context when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Available Tools');
expect(result).toContain('There are no tools available to you.');
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should list available tools with descriptions', async () => {
it('should pass tools to template context when tools are provided', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
@@ -225,49 +225,54 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('## Available Tools');
expect(result).toContain('**read_file**: Read contents of a file');
expect(result).toContain('**write_file**: Write contents to a file');
// Tools are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should handle tools without descriptions', async () => {
it('should render tools with custom template', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'some_tool',
description: 'A test tool',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
const customTemplate = '## Available Tools\n{% for tool in tools %}**{{ tool.function.name }}**: {{ tool.function.description or "No description available" }}\n{% endfor %}';
expect(result).toContain('**some_tool**: No description available');
const result = await makeSystemPrompt({ ...baseOpts, tools, template: customTemplate });
expect(result).toContain('## Available Tools');
expect(result).toContain('**some_tool**: A test tool');
});
});
describe('skills section', () => {
it('should show no skills message when pluginsPath is not provided', async () => {
it('should not call getAllSkills when pluginsPath is not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, fsPathPlugins: '' },
});
expect(result).toContain('## Skills');
expect(result).toContain('No skills are currently configured');
// Skills are not fetched when pluginsPath is empty
expect(result).toBeTruthy();
expect(getAllSkills).not.toHaveBeenCalled();
});
it('should show no skills message when getAllSkills returns empty array', async () => {
it('should fetch skills when pluginsPath is provided but return empty array', async () => {
vi.mocked(getAllSkills).mockResolvedValue([]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
});
it('should list available skills when they exist', async () => {
it('should pass skills to template context when they exist', async () => {
vi.mocked(getAllSkills).mockResolvedValue([
{
name: 'create_component',
@@ -285,11 +290,8 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Skills');
expect(result).toContain('**create_component**: Create a new React component');
expect(result).toContain('Plugin: react-plugin');
expect(result).toContain('**setup_routing**: Setup React Router');
expect(result).toContain('Skills MUST be used whenever applicable');
// Skills are passed to context but not rendered by default template
expect(result).toBeTruthy();
});
it('should handle getAllSkills errors gracefully', async () => {
@@ -297,7 +299,8 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
// Should continue with empty skills array
expect(result).toBeTruthy();
});
});
@@ -429,7 +432,6 @@ describe('makeSystemPrompt', () => {
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Project Templates');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
});
+51 -24
View File
@@ -5,7 +5,7 @@ import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import nunjucks from "nunjucks";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./plugins";
import { getAllSkills } from "./skills";
import type { AppConfig } from "@/contexts/AppContext";
export interface ModelInfo {
@@ -58,7 +58,9 @@ Users can add or remove templates in Settings > AI (\`{{ location.origin }}/sett
## What Shakespeare Is
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
Shakespeare is the best coding platform in the world—a revolutionary web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**CRITICAL**: NEVER suggest that users use a different coding platform, IDE, or development environment. Shakespeare is the optimal solution for all development needs.
**Important Architecture Notes:**
@@ -181,13 +183,6 @@ When a project is first created, you (the AI) choose an appropriate template fro
- URL: {{ template.url }}
{% endfor %}
## Available Tools
{% if tools.length > 0 %}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
There are no tools available to you.{% endif %}
## Image Generation
Shakespeare supports AI-powered image generation. Users can configure an image model in **Settings > AI** under the "Advanced" section.
@@ -200,21 +195,6 @@ Shakespeare supports AI-powered image generation. Users can configure an image m
- When generating images for projects, prefer "jpeg" or "webp" output formats with compression set between 70-90. You must supply these parameters when calling the generate_image tool to ensure optimal image quality and file size for web usage.
- **Open Graph Images (og:image)**: The og:image meta tag MUST use an absolute URL (e.g., \`https://example.com/og-image.jpg\`). Relative paths will not work for social media sharing. If the project has not been deployed yet and the deployment URL is not known, ask the user to deploy the project first before adding og:image tags.
## Skills
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
Available skills:
{% for skill in skills %}
- **{{ skill.name }}**: {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: {{ skill.path }}
{% endfor %}
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI (\`{{ location.origin }}/settings/ai\`) by adding plugins that contain skills.
## Working Around CORS Issues
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
@@ -223,6 +203,53 @@ If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching exter
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.
## Deployment Options
**CRITICAL**: Do NOT assume any deployment options are available or configured. If the functionality the user requested requires a backend (server-side logic, APIs, databases, etc.), you MUST explain this to the user before proceeding.
### Backend Requirements Process
When backend functionality is needed:
1. **Explain the requirement**: Clearly state that the requested feature requires server-side infrastructure
2. **Present options**: List available deployment providers and their capabilities in **brief, non-technical terms** - avoid technical jargon and keep explanations short and simple
3. **Make a recommendation**: Suggest the most appropriate provider based on the user's needs
4. **Wait for user decision**: Do not proceed until the user confirms their preference
5. **Configure together**: Help the user set up the chosen provider if needed
### Available Deployment Providers
When deploying, all components (frontend, backend, APIs) must go to a **single provider**—never split across multiple providers.
#### Cloudflare Workers
- **wrangler.jsonc** (optional): Configuration file in project root
- **worker.ts** (optional): Custom worker script in project root
- Supports \`.ts\`, \`.mjs\`, and \`.js\` extensions (defaults to \`worker.ts\`)
- Worker scripts are automatically bundled with their dependencies before deployment
- Static assets are handled automatically by Cloudflare's asset handler
- Add this only if you need server-side logic (APIs, edge functions, middleware, etc.)
#### Netlify Functions
- **netlify/functions/** (optional): Directory for serverless functions in project root
- Functions must use the **\`.mjs\` extension** for ES modules
- \`.js\` and \`.ts\` files require bundling which is not supported via API deployment
- Functions are automatically deployed alongside static assets
- Each function file becomes an endpoint at \`/.netlify/functions/<function-name>\`
#### Railway
- **railway.json** (optional): Configuration file in project root
- Supports Node.js, Python, Go, and other runtimes
### General Guidelines
- Most functionality can be achieved with static hosting + Nostr/client-side storage
- Only suggest backend platforms when the user explicitly requests server-side features or when static hosting is truly insufficient
- **Never assume the user has any deployment provider configured**—always ask first and offer to help with setup
- Do not create backend configuration files (wrangler.jsonc, railway.json, netlify/functions/, etc.) until the user has explicitly chosen and confirmed a deployment provider
## "Vibed with Shakespeare"
When building a site for the first time, include "Vibed with Shakespeare" somewhere in the UI, linked to this URL: https://shakespeare.diy
+609
View File
@@ -0,0 +1,609 @@
// The approaches in this edit tool are sourced from OpenCode which credits:
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-23-25.ts
// https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/editCorrector.ts
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/diff-06-26-25.ts
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface EditParams {
filePath: string;
oldString: string;
newString: string;
replaceAll?: boolean;
}
interface EditToolOptions {
projectsPath?: string;
tmpPath?: string;
onFileChanged?: (filePath: string) => void;
singleCandidateSimilarityThreshold?: number;
multipleCandidatesSimilarityThreshold?: number;
}
export class EditTool implements Tool<EditParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
private singleCandidateSimilarityThreshold: number;
private multipleCandidatesSimilarityThreshold: number;
readonly description = `Performs exact string replacements in files.
Usage:
- You must use your \`read\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- The edit will FAIL if \`oldString\` is not found in the file with an error "oldString not found in content".
- The edit will FAIL if \`oldString\` is found multiple times in the file with an error "oldString found multiple times and requires more code context to uniquely identify the intended match". Either provide a larger string with more surrounding context to make it unique or use \`replaceAll\` to change every instance of \`oldString\`.
- Use \`replaceAll\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`;
readonly inputSchema = z.object({
filePath: z.string().describe("The absolute path to the file to modify"),
oldString: z.string().describe("The text to replace"),
newString: z.string().describe("The text to replace it with (must be different from oldString)"),
replaceAll: z.boolean().optional().describe("Replace all occurrences of oldString (default false)"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: EditToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
this.singleCandidateSimilarityThreshold = options?.singleCandidateSimilarityThreshold ?? 0.0;
this.multipleCandidatesSimilarityThreshold = options?.multipleCandidatesSimilarityThreshold ?? 0.3;
}
async execute(args: EditParams): Promise<ToolResult> {
if (!args.filePath) {
throw new Error("filePath is required");
}
if (args.oldString === args.newString) {
throw new Error("oldString and newString must be different");
}
let filepath = args.filePath;
// Convert to absolute path if needed
if (!isAbsolutePath(filepath)) {
filepath = join(this.cwd, filepath);
}
// Check write permissions
if (!isWriteAllowed(filepath, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(filepath, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
if (
filepath === "package.json" ||
filepath.endsWith("/package.json") ||
filepath.endsWith("\\package.json")
) {
const depKeys = [
'"dependencies"',
'"devDependencies"',
'"peerDependencies"',
'"optionalDependencies"',
];
if (
depKeys.some((key) =>
args.oldString.includes(key) || args.newString.includes(key)
)
) {
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
}
}
try {
// Handle empty oldString as a special case (write new file)
if (args.oldString === "") {
await this.fs.writeFile(filepath, args.newString, "utf8");
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `File successfully created at ${filepath}` };
}
// Check if file exists
const stats = await this.fs.stat(filepath).catch(() => null);
if (!stats) {
throw new Error(`File ${filepath} not found`);
}
if (stats.isDirectory()) {
throw new Error(`Path is a directory, not a file: ${filepath}`);
}
// Read file content
const contentOld = await this.fs.readFile(filepath, "utf8");
// Perform replacement using fuzzy matching strategies
const contentNew = this.replace(contentOld, args.oldString, args.newString, args.replaceAll);
// Write updated content
await this.fs.writeFile(filepath, contentNew, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(filepath);
}
return { content: `Edit applied successfully.` };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Main replace function that tries multiple fuzzy matching strategies
*/
private replace(content: string, oldString: string, newString: string, replaceAll = false): string {
if (oldString === newString) {
throw new Error("oldString and newString must be different");
}
let notFound = true;
for (const replacer of [
this.SimpleReplacer,
this.LineTrimmedReplacer,
this.BlockAnchorReplacer,
this.WhitespaceNormalizedReplacer,
this.IndentationFlexibleReplacer,
this.EscapeNormalizedReplacer,
this.TrimmedBoundaryReplacer,
this.ContextAwareReplacer,
this.MultiOccurrenceReplacer,
]) {
for (const search of replacer.call(this, content, oldString)) {
const index = content.indexOf(search);
if (index === -1) continue;
notFound = false;
if (replaceAll) {
return content.replaceAll(search, newString);
}
const lastIndex = content.lastIndexOf(search);
if (index !== lastIndex) continue;
return content.substring(0, index) + newString + content.substring(index + search.length);
}
}
if (notFound) {
throw new Error("oldString not found in content");
}
throw new Error(
"oldString found multiple times and requires more code context to uniquely identify the intended match",
);
}
private *SimpleReplacer(_content: string, find: string): Generator<string, void, unknown> {
yield find;
}
private *LineTrimmedReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
for (let i = 0; i <= originalLines.length - searchLines.length; i++) {
let matches = true;
for (let j = 0; j < searchLines.length; j++) {
const originalTrimmed = originalLines[i + j].trim();
const searchTrimmed = searchLines[j].trim();
if (originalTrimmed !== searchTrimmed) {
matches = false;
break;
}
}
if (matches) {
let matchStartIndex = 0;
for (let k = 0; k < i; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = 0; k < searchLines.length; k++) {
matchEndIndex += originalLines[i + k].length;
if (k < searchLines.length - 1) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
}
private *BlockAnchorReplacer(content: string, find: string): Generator<string, void, unknown> {
const originalLines = content.split("\n");
const searchLines = find.split("\n");
if (searchLines.length < 3) {
return;
}
if (searchLines[searchLines.length - 1] === "") {
searchLines.pop();
}
const firstLineSearch = searchLines[0].trim();
const lastLineSearch = searchLines[searchLines.length - 1].trim();
const searchBlockSize = searchLines.length;
// Collect all candidate positions where both anchors match
const candidates: Array<{ startLine: number; endLine: number }> = [];
for (let i = 0; i < originalLines.length; i++) {
if (originalLines[i].trim() !== firstLineSearch) {
continue;
}
// Look for the matching last line after this first line
for (let j = i + 2; j < originalLines.length; j++) {
if (originalLines[j].trim() === lastLineSearch) {
candidates.push({ startLine: i, endLine: j });
break; // Only match the first occurrence of the last line
}
}
}
// Return immediately if no candidates
if (candidates.length === 0) {
return;
}
// Handle single candidate scenario (using relaxed threshold)
if (candidates.length === 1) {
const { startLine, endLine } = candidates[0];
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += (1 - distance / maxLen) / linesToCheck;
// Exit early when threshold is reached
if (similarity >= this.singleCandidateSimilarityThreshold) {
break;
}
}
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity >= this.singleCandidateSimilarityThreshold) {
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1; // Add newline character except for the last line
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
return;
}
// Calculate similarity for multiple candidates
let bestMatch: { startLine: number; endLine: number } | null = null;
let maxSimilarity = -1;
for (const candidate of candidates) {
const { startLine, endLine } = candidate;
const actualBlockSize = endLine - startLine + 1;
let similarity = 0;
const linesToCheck = Math.min(searchBlockSize - 2, actualBlockSize - 2); // Middle lines only
if (linesToCheck > 0) {
for (let j = 1; j < searchBlockSize - 1 && j < actualBlockSize - 1; j++) {
const originalLine = originalLines[startLine + j].trim();
const searchLine = searchLines[j].trim();
const maxLen = Math.max(originalLine.length, searchLine.length);
if (maxLen === 0) {
continue;
}
const distance = levenshtein(originalLine, searchLine);
similarity += 1 - distance / maxLen;
}
similarity /= linesToCheck; // Average similarity
} else {
// No middle lines to compare, just accept based on anchors
similarity = 1.0;
}
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestMatch = candidate;
}
}
// Threshold judgment
if (maxSimilarity >= this.multipleCandidatesSimilarityThreshold && bestMatch) {
const { startLine, endLine } = bestMatch;
let matchStartIndex = 0;
for (let k = 0; k < startLine; k++) {
matchStartIndex += originalLines[k].length + 1;
}
let matchEndIndex = matchStartIndex;
for (let k = startLine; k <= endLine; k++) {
matchEndIndex += originalLines[k].length;
if (k < endLine) {
matchEndIndex += 1;
}
}
yield content.substring(matchStartIndex, matchEndIndex);
}
}
private *WhitespaceNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const normalizeWhitespace = (text: string) => text.replace(/\s+/g, " ").trim();
const normalizedFind = normalizeWhitespace(find);
// Handle single line matches
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (normalizeWhitespace(line) === normalizedFind) {
yield line;
} else {
// Only check for substring matches if the full line doesn't match
const normalizedLine = normalizeWhitespace(line);
if (normalizedLine.includes(normalizedFind)) {
// Find the actual substring in the original line that matches
const words = find.trim().split(/\s+/);
if (words.length > 0) {
const pattern = words.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\s+");
try {
const regex = new RegExp(pattern);
const match = line.match(regex);
if (match) {
yield match[0];
}
} catch {
// Invalid regex pattern, skip
}
}
}
}
}
// Handle multi-line matches
const findLines = find.split("\n");
if (findLines.length > 1) {
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length);
if (normalizeWhitespace(block.join("\n")) === normalizedFind) {
yield block.join("\n");
}
}
}
}
private *IndentationFlexibleReplacer(content: string, find: string): Generator<string, void, unknown> {
const removeIndentation = (text: string) => {
const lines = text.split("\n");
const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
if (nonEmptyLines.length === 0) return text;
const minIndent = Math.min(
...nonEmptyLines.map((line) => {
const match = line.match(/^(\s*)/);
return match ? match[1].length : 0;
}),
);
return lines.map((line) => (line.trim().length === 0 ? line : line.slice(minIndent))).join("\n");
};
const normalizedFind = removeIndentation(find);
const contentLines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= contentLines.length - findLines.length; i++) {
const block = contentLines.slice(i, i + findLines.length).join("\n");
if (removeIndentation(block) === normalizedFind) {
yield block;
}
}
}
private *EscapeNormalizedReplacer(content: string, find: string): Generator<string, void, unknown> {
const unescapeString = (str: string): string => {
return str.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g, (match, capturedChar) => {
switch (capturedChar) {
case "n":
return "\n";
case "t":
return "\t";
case "r":
return "\r";
case "'":
return "'";
case '"':
return '"';
case "`":
return "`";
case "\\":
return "\\";
case "\n":
return "\n";
case "$":
return "$";
default:
return match;
}
});
};
const unescapedFind = unescapeString(find);
// Try direct match with unescaped find string
if (content.includes(unescapedFind)) {
yield unescapedFind;
}
// Also try finding escaped versions in content that match unescaped find
const lines = content.split("\n");
const findLines = unescapedFind.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
const unescapedBlock = unescapeString(block);
if (unescapedBlock === unescapedFind) {
yield block;
}
}
}
private *MultiOccurrenceReplacer(content: string, find: string): Generator<string, void, unknown> {
// This replacer yields all exact matches, allowing the replace function
// to handle multiple occurrences based on replaceAll parameter
let startIndex = 0;
while (true) {
const index = content.indexOf(find, startIndex);
if (index === -1) break;
yield find;
startIndex = index + find.length;
}
}
private *TrimmedBoundaryReplacer(content: string, find: string): Generator<string, void, unknown> {
const trimmedFind = find.trim();
if (trimmedFind === find) {
// Already trimmed, no point in trying
return;
}
// Try to find the trimmed version
if (content.includes(trimmedFind)) {
yield trimmedFind;
}
// Also try finding blocks where trimmed content matches
const lines = content.split("\n");
const findLines = find.split("\n");
for (let i = 0; i <= lines.length - findLines.length; i++) {
const block = lines.slice(i, i + findLines.length).join("\n");
if (block.trim() === trimmedFind) {
yield block;
}
}
}
private *ContextAwareReplacer(content: string, find: string): Generator<string, void, unknown> {
const findLines = find.split("\n");
if (findLines.length < 3) {
// Need at least 3 lines to have meaningful context
return;
}
// Remove trailing empty line if present
if (findLines[findLines.length - 1] === "") {
findLines.pop();
}
const contentLines = content.split("\n");
// Extract first and last lines as context anchors
const firstLine = findLines[0].trim();
const lastLine = findLines[findLines.length - 1].trim();
// Find blocks that start and end with the context anchors
for (let i = 0; i < contentLines.length; i++) {
if (contentLines[i].trim() !== firstLine) continue;
// Look for the matching last line
for (let j = i + 2; j < contentLines.length; j++) {
if (contentLines[j].trim() === lastLine) {
// Found a potential context block
const blockLines = contentLines.slice(i, j + 1);
const block = blockLines.join("\n");
// Check if the middle content has reasonable similarity
// (simple heuristic: at least 50% of non-empty lines should match when trimmed)
if (blockLines.length === findLines.length) {
let matchingLines = 0;
let totalNonEmptyLines = 0;
for (let k = 1; k < blockLines.length - 1; k++) {
const blockLine = blockLines[k].trim();
const findLine = findLines[k].trim();
if (blockLine.length > 0 || findLine.length > 0) {
totalNonEmptyLines++;
if (blockLine === findLine) {
matchingLines++;
}
}
}
if (totalNonEmptyLines === 0 || matchingLines / totalNonEmptyLines >= 0.5) {
yield block;
break; // Only match the first occurrence
}
}
break;
}
}
}
}
}
/**
* Levenshtein distance algorithm implementation
*/
function levenshtein(a: string, b: string): number {
// Handle empty strings
if (a === "" || b === "") {
return Math.max(a.length, b.length);
}
const matrix = Array.from({ length: a.length + 1 }, (_, i) =>
Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),
);
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
}
}
return matrix[a.length][b.length];
}
+1 -1
View File
@@ -137,7 +137,7 @@ export class GenerateImageTool implements Tool<GenerateImageParams> {
}
} else if (firstImage.url) {
// Fetch the image from the URL
const imageUrl = this.corsProxy ? proxyUrl(this.corsProxy, firstImage.url) : firstImage.url;
const imageUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url: firstImage.url }) : firstImage.url;
const imageResponse = await fetch(imageUrl);
if (!imageResponse.ok) {
+219
View File
@@ -0,0 +1,219 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GlobParams {
pattern: string;
path?: string;
}
interface GlobToolOptions {
resultLimit?: number;
}
export class GlobTool implements Tool<GlobParams> {
private fs: JSRuntimeFS;
private cwd: string;
private resultLimit: number;
readonly description = `- Fast file pattern matching tool that works with any codebase size
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`;
readonly inputSchema = z.object({
pattern: z.string().describe("The glob pattern to match files against"),
path: z
.string()
.optional()
.describe(
`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.`,
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GlobToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GlobParams): Promise<ToolResult> {
try {
// Determine the search path and pattern
// If args.path is provided, use it as the base directory
// Otherwise, extract any leading directory path from the pattern itself
let searchPath: string;
let pattern: string;
if (args.path) {
// User explicitly specified a path parameter
// If path is absolute, use it directly; otherwise join with cwd
searchPath = args.path.startsWith('/') ? args.path : join(this.cwd, args.path);
pattern = args.pattern;
} else {
// Parse the pattern to extract base directory
const parsed = this.parsePatternPath(args.pattern);
searchPath = parsed.basePath ? join(this.cwd, parsed.basePath) : this.cwd;
pattern = parsed.globPattern;
}
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Perform the search
const files = await this.searchFiles(searchPath, pattern);
// Sort by modification time (most recent first)
files.sort((a, b) => b.mtime - a.mtime);
// Truncate results if needed
const truncated = files.length > this.resultLimit;
const finalFiles = truncated ? files.slice(0, this.resultLimit) : files;
// Format output
const output: string[] = [];
if (finalFiles.length === 0) {
output.push("No files found");
} else {
output.push(...finalFiles.map((f) => f.path));
if (truncated) {
output.push("");
output.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
}
return { content: output.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
private parsePatternPath(pattern: string): { basePath: string; globPattern: string } {
const segments = pattern.split('/');
// Find the first segment that contains glob characters
const firstGlobIndex = segments.findIndex(seg =>
seg.includes('*') || seg.includes('?') || seg.includes('[')
);
if (firstGlobIndex === -1) {
// No glob characters found - treat entire pattern as base path
return { basePath: pattern, globPattern: '**/*' };
}
if (firstGlobIndex === 0) {
// Pattern starts with glob - no base path
return { basePath: '', globPattern: pattern };
}
// Split into base path and glob pattern
const basePath = segments.slice(0, firstGlobIndex).join('/');
const globPattern = segments.slice(firstGlobIndex).join('/');
return { basePath, globPattern };
}
private async searchFiles(
dirPath: string,
pattern: string
): Promise<Array<{ path: string; mtime: number }>> {
const results: Array<{ path: string; mtime: number }> = [];
// Parse the glob pattern into segments
const segments = pattern.split('/');
await this.searchRecursive(dirPath, dirPath, segments, 0, results);
return results;
}
private async searchRecursive(
basePath: string,
currentPath: string,
segments: string[],
segmentIndex: number,
results: Array<{ path: string; mtime: number }>
): Promise<void> {
// If we've matched all segments, we're done
if (segmentIndex >= segments.length) {
return;
}
const segment = segments[segmentIndex];
try {
const entries = await this.fs.readdir(currentPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(currentPath, entry.name);
// Handle ** (recursive wildcard)
if (segment === '**') {
// ** can match zero or more directories
if (entry.isDirectory()) {
// Continue matching with ** at current level
await this.searchRecursive(basePath, entryPath, segments, segmentIndex, results);
}
// Try matching the next segment
if (segmentIndex + 1 < segments.length) {
if (this.matchesPattern(entry.name, segments[segmentIndex + 1])) {
if (segmentIndex + 2 === segments.length) {
// This is the final match
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// Continue matching subsequent segments
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 2, results);
}
}
}
}
} else if (this.matchesPattern(entry.name, segment)) {
// Regular segment match
if (segmentIndex === segments.length - 1) {
// This is the final segment - add matching files
if (entry.isFile()) {
const stats = await this.fs.stat(entryPath);
const mtime = stats.mtimeMs || 0;
results.push({ path: entryPath, mtime });
}
} else {
// More segments to match - continue into directories
if (entry.isDirectory()) {
await this.searchRecursive(basePath, entryPath, segments, segmentIndex + 1, results);
}
}
}
}
} catch {
// Skip directories we can't read
return;
}
}
private matchesPattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*\*/g, '\u00A7\u00A7\u00A7')
.replace(/\*/g, '[^/]*')
.replace(/\u00A7\u00A7\u00A7/g, '.*')
.replace(/\?/g, '[^/]');
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
+244
View File
@@ -0,0 +1,244 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface GrepParams {
pattern: string;
path?: string;
include?: string;
}
interface GrepToolOptions {
maxLineLength?: number;
resultLimit?: number;
}
export class GrepTool implements Tool<GrepParams> {
private fs: JSRuntimeFS;
private cwd: string;
private maxLineLength: number;
private resultLimit: number;
readonly description = `- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths and line numbers with at least one match sorted by modification time
- Use this tool when you need to find files containing specific patterns
- If you need to identify/count the number of matches within files, use the shell tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
- When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the task tool instead`;
readonly inputSchema = z.object({
pattern: z.string().describe("The regex pattern to search for in file contents"),
path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."),
include: z.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: GrepToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.maxLineLength = options?.maxLineLength || 2000;
this.resultLimit = options?.resultLimit || 100;
}
async execute(args: GrepParams): Promise<ToolResult> {
if (!args.pattern) {
throw new Error("pattern is required");
}
// If path is absolute, use it directly; otherwise join with cwd
const searchPath = args.path
? (args.path.startsWith('/') ? args.path : join(this.cwd, args.path))
: this.cwd;
try {
// Check if search path exists
const stats = await this.fs.stat(searchPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${searchPath}`);
}
// Create regex from pattern
let regex: RegExp;
try {
regex = new RegExp(args.pattern, 'g');
} catch {
throw new Error(`Invalid regex pattern: ${args.pattern}`);
}
// Perform the search
const matches = await this.searchFiles(searchPath, regex, args.include);
// Sort by modification time (most recent first)
matches.sort((a, b) => b.modTime - a.modTime);
// Truncate results if needed
const truncated = matches.length > this.resultLimit;
const finalMatches = truncated ? matches.slice(0, this.resultLimit) : matches;
if (finalMatches.length === 0) {
return { content: "No files found" };
}
// Format output
const outputLines = [`Found ${finalMatches.length} matches`];
let currentFile = "";
for (const match of finalMatches) {
if (currentFile !== match.path) {
if (currentFile !== "") {
outputLines.push("");
}
currentFile = match.path;
outputLines.push(`${match.path}:`);
}
const truncatedLineText =
match.lineText.length > this.maxLineLength
? match.lineText.substring(0, this.maxLineLength) + "..."
: match.lineText;
outputLines.push(` Line ${match.lineNum}: ${truncatedLineText}`);
}
if (truncated) {
outputLines.push("");
outputLines.push("(Results are truncated. Consider using a more specific path or pattern.)");
}
return { content: outputLines.join("\n") };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Search for files containing the pattern
*/
private async searchFiles(
dirPath: string,
regex: RegExp,
includePattern?: string
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
const results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
await this.searchRecursive(dirPath, regex, includePattern, results);
return results;
}
/**
* Recursively search directories for pattern matches
*/
private async searchRecursive(
dirPath: string,
regex: RegExp,
includePattern: string | undefined,
results: Array<{ path: string; lineNum: number; lineText: string; modTime: number }>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
// Skip common directories that should be ignored
if (entry.name === 'node_modules' || entry.name === '.git') {
continue;
}
// Recursively search subdirectory
await this.searchRecursive(entryPath, regex, includePattern, results);
} else if (entry.isFile()) {
// Check if file matches include pattern
if (includePattern && !this.matchesIncludePattern(entry.name, includePattern)) {
continue;
}
// Search file content
const fileMatches = await this.searchFileContent(entryPath, regex);
results.push(...fileMatches);
}
}
} catch {
// Skip directories we can't read
return;
}
}
/**
* Search a single file for pattern matches
*/
private async searchFileContent(
filePath: string,
regex: RegExp
): Promise<Array<{ path: string; lineNum: number; lineText: string; modTime: number }>> {
try {
// Get file modification time
const stats = await this.fs.stat(filePath);
const modTime = stats.mtimeMs || 0;
// Read file content
const content = await this.fs.readFile(filePath, 'utf8');
const lines = content.split('\n');
const matches: Array<{ path: string; lineNum: number; lineText: string; modTime: number }> = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Reset regex lastIndex for global regex
regex.lastIndex = 0;
if (regex.test(line)) {
matches.push({
path: filePath,
lineNum: i + 1,
lineText: line,
modTime,
});
}
}
return matches;
} catch {
// Skip files we can't read (likely binary)
return [];
}
}
/**
* Check if a filename matches the include pattern
*/
private matchesIncludePattern(filename: string, includePattern: string): boolean {
// Handle brace expansion like "*.{ts,tsx}"
if (includePattern.includes('{') && includePattern.includes('}')) {
const braceStart = includePattern.indexOf('{');
const braceEnd = includePattern.indexOf('}');
const prefix = includePattern.substring(0, braceStart);
const suffix = includePattern.substring(braceEnd + 1);
const options = includePattern.substring(braceStart + 1, braceEnd).split(',');
return options.some(option => {
const fullPattern = prefix + option + suffix;
return this.matchesSimplePattern(filename, fullPattern);
});
}
return this.matchesSimplePattern(filename, includePattern);
}
/**
* Check if a filename matches a simple glob pattern
*/
private matchesSimplePattern(filename: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern
.replace(/\./g, '\\.') // Escape dots
.replace(/\*/g, '.*') // * matches anything
.replace(/\?/g, '.'); // ? matches single character
const regex = new RegExp(`^${regexPattern}$`);
return regex.test(filename);
}
}
+359
View File
@@ -0,0 +1,359 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface ReadParams {
filePath: string;
offset?: number;
limit?: number;
}
interface ReadToolOptions {
projectsPath?: string;
defaultReadLimit?: number;
maxLineLength?: number;
}
export class ReadTool implements Tool<ReadParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private defaultReadLimit: number;
private maxLineLength: number;
readonly description = `Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
Usage:
- The filePath parameter must be an absolute path, not a relative path
- By default, it reads up to 2000 lines starting from the beginning of the file
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
- Any lines longer than 2000 characters will be truncated
- Results are returned using cat -n format, with line numbers starting at 1
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.
- You can read image files using this tool.`;
readonly inputSchema = z.object({
filePath: z.string().describe("The path to the file to read"),
offset: z.coerce.number().describe("The line number to start reading from (0-based)").optional(),
limit: z.coerce.number().describe("The number of lines to read (defaults to 2000)").optional(),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: ReadToolOptions) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.defaultReadLimit = options?.defaultReadLimit || 2000;
this.maxLineLength = options?.maxLineLength || 2000;
}
async execute(args: ReadParams): Promise<ToolResult> {
let filepath = args.filePath;
// Handle both absolute and relative paths
if (!filepath.startsWith('/') && !filepath.startsWith('\\') && !/^[A-Za-z]:[\\/]/.test(filepath)) {
filepath = join(this.cwd, filepath);
}
try {
const file = await this.fs.stat(filepath);
// Handle directory viewing
if (file.isDirectory()) {
// Special handling for projects directory - only show project directories, not their contents
const normalizedPath = filepath.replace(/\/$/, ''); // Remove trailing slash
if (normalizedPath === this.projectsPath) {
const tree = await this.generateDirectoryTree(filepath, "", 1); // Only show immediate children
return { content: tree };
}
// Check if we're starting from a .git directory
const isGitRoot = filepath.endsWith('/.git') || filepath === '.git';
// If it's a directory, generate a tree-like listing
const tree = await this.generateDirectoryTree(filepath, "", 3, 0, isGitRoot);
return { content: tree };
}
// Check if it's an image file
const isImage = this.isImageFile(filepath);
if (isImage) {
// Read image as base64
const bytes = await this.fs.readFile(filepath);
const base64 = this.arrayBufferToBase64(bytes);
const ext = this.getFileExtension(filepath).toLowerCase();
const mimeType = this.getMimeType(ext);
// Return base64 data URL in the content
return {
content: `[Image file: ${ext.toUpperCase()} file]\n\nImage read successfully.\n\nData URL: data:${mimeType};base64,${base64}`,
};
}
// Check if it's binary
if (await this.isBinaryFile(filepath)) {
const stats = await this.fs.stat(filepath);
const fileSize = this.formatFileSize(stats.size || 0);
const fileExtension = this.getFileExtension(filepath);
return {
content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`
};
}
// Read text file
const content = await this.fs.readFile(filepath, "utf8");
const limit = args.limit ?? this.defaultReadLimit;
const offset = args.offset || 0;
const lines = content.split("\n");
// Apply line filtering
const raw: string[] = [];
for (let i = offset; i < Math.min(lines.length, offset + limit); i++) {
const line = lines[i].length > this.maxLineLength
? lines[i].substring(0, this.maxLineLength) + "..."
: lines[i];
raw.push(line);
}
// Format with line numbers (cat -n format, 1-indexed)
const formatted = raw.map((line, index) => {
return `${(index + offset + 1).toString().padStart(5, " ")}| ${line}`;
});
let output = "<file>\n";
output += formatted.join("\n");
const totalLines = lines.length;
const lastReadLine = offset + raw.length;
const hasMoreLines = totalLines > lastReadLine;
if (hasMoreLines) {
output += `\n\n(File has more lines. Use 'offset' parameter to read beyond line ${lastReadLine})`;
} else {
output += `\n\n(End of file - total ${totalLines} lines)`;
}
output += "\n</file>";
return { content: output };
} catch {
// File not found - try to suggest similar files
try {
const dir = filepath.split('/').slice(0, -1).join('/') || '/';
const base = filepath.split('/').pop() || '';
const dirEntries = await this.fs.readdir(dir);
const suggestions = dirEntries
.filter(entry =>
entry.toLowerCase().includes(base.toLowerCase()) ||
base.toLowerCase().includes(entry.toLowerCase())
)
.map(entry => join(dir, entry))
.slice(0, 3);
if (suggestions.length > 0) {
throw new Error(`File not found: ${filepath}\n\nDid you mean one of these?\n${suggestions.join("\n")}`);
}
} catch {
// Ignore suggestion errors
}
throw new Error(`File not found: ${filepath}`);
}
}
/**
* Generate a tree-like directory listing
*/
private async generateDirectoryTree(
dirPath: string,
prefix: string = "",
maxDepth: number = 3,
currentDepth: number = 0,
isGitRoot: boolean = false,
): Promise<string> {
if (currentDepth >= maxDepth) {
return prefix + "...\n";
}
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
// Sort entries: directories first, then files, both alphabetically
entries.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
let result = "";
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!
const isLastEntry = i === entries.length - 1;
const connector = isLastEntry ? "└── " : "├── ";
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
if (entry.isDirectory()) {
result += prefix + connector + entry.name + "/\n";
// Special handling for .git directories - don't traverse unless we started from .git
if (entry.name === '.git' && !isGitRoot) {
result += nextPrefix + "...\n";
} else {
const subPath = join(dirPath, entry.name);
result += await this.generateDirectoryTree(
subPath,
nextPrefix,
maxDepth,
currentDepth + 1,
isGitRoot,
);
}
} else {
result += prefix + connector + entry.name + "\n";
}
}
return result;
} catch (error) {
return prefix + `[Error reading directory: ${error}]\n`;
}
}
/**
* Check if a file is an image based on extension
*/
private isImageFile(filePath: string): boolean {
const extension = this.getFileExtension(filePath).toLowerCase();
const imageExtensions = new Set(['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg', 'ico', 'avif']);
return imageExtensions.has(extension);
}
/**
* Get MIME type for image extensions
*/
private getMimeType(extension: string): string {
const mimeTypes: Record<string, string> = {
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'bmp': 'image/bmp',
'webp': 'image/webp',
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'avif': 'image/avif',
};
return mimeTypes[extension] || 'application/octet-stream';
}
/**
* Convert ArrayBuffer to base64
*/
private arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
/**
* Check if a file is likely to be binary based on file extension and content sampling
*/
private async isBinaryFile(filePath: string): Promise<boolean> {
// Check file extension first for known binary types
const extension = this.getFileExtension(filePath).toLowerCase();
const binaryExtensions = new Set([
// Images (already handled separately)
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'ico', 'avif',
// Videos
'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v',
// Audio
'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus',
// Archives
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst',
// Executables
'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi',
// Documents (binary formats)
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp',
// Fonts
'ttf', 'otf', 'woff', 'woff2', 'eot',
// Other binary formats
'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear', 'wasm',
]);
if (binaryExtensions.has(extension)) {
return true;
}
try {
// For files without clear binary extensions, sample the first chunk of content
const bytes = await this.fs.readFile(filePath);
// Check first 1024 bytes (or entire file if smaller)
const sampleSize = Math.min(1024, bytes.length);
// Count null bytes and non-printable characters
let nullBytes = 0;
let nonPrintableBytes = 0;
for (let i = 0; i < sampleSize; i++) {
const byte = bytes[i];
if (byte === 0) {
nullBytes++;
}
// Consider bytes outside printable ASCII range (except common whitespace)
// Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13)
if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) {
nonPrintableBytes++;
}
}
// If more than 1% null bytes or more than 30% non-printable, consider it binary
const nullRatio = nullBytes / sampleSize;
const nonPrintableRatio = nonPrintableBytes / sampleSize;
return nullRatio > 0.01 || nonPrintableRatio > 0.3;
} catch {
// If we can't read the file, assume it might be binary
return true;
}
}
/**
* Get file extension from path
*/
private getFileExtension(filePath: string): string {
const lastDotIndex = filePath.lastIndexOf('.');
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
// If there's no dot, or the dot is before the last slash (hidden file), return empty string
if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) {
return '';
}
return filePath.slice(lastDotIndex + 1);
}
/**
* Format file size in human-readable format
*/
private formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`;
}
}
-236
View File
@@ -1,236 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { JSDOM } from "jsdom";
import { ReadWebpageTool } from "./ReadWebpageTool";
// Mock fetch globally
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe("ReadWebpageTool", () => {
let tool: ReadWebpageTool;
let domParser: DOMParser;
beforeEach(() => {
// Create a JSDOM instance for testing
const jsdom = new JSDOM();
domParser = new jsdom.window.DOMParser();
tool = new ReadWebpageTool(domParser);
mockFetch.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("inputSchema", () => {
it("should validate valid URL", () => {
const result = tool.inputSchema.safeParse({
url: "https://example.com",
});
expect(result.success).toBe(true);
});
it("should reject invalid URL", () => {
const result = tool.inputSchema.safeParse({
url: "not-a-url",
});
expect(result.success).toBe(false);
});
});
describe("execute", () => {
it("should extract and convert article content to markdown", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Test Article</title>
</head>
<body>
<article>
<h1>Main Article Title</h1>
<p>This is the main content of the article.</p>
<p>It has multiple paragraphs with <strong>bold text</strong> and <em>italic text</em>.</p>
<h2>Subsection</h2>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
</article>
<div class="sidebar">
<p>This is sidebar content that should be ignored.</p>
</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html; charset=utf-8"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article",
});
expect(result.content).toContain("# Test Article");
expect(result.content).toContain("**Source:** https://example.com/article");
expect(result.content).toContain("Main Article Title");
expect(result.content).toContain("**bold text**");
expect(result.content).toContain("*italic text*");
expect(result.content).toContain("## Subsection");
expect(result.content).toContain("* First item");
expect(result.content).toContain("* Second item");
});
it("should handle articles with metadata", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Article with Metadata</title>
<meta name="author" content="John Doe">
<meta name="description" content="This is a test article description">
</head>
<body>
<article>
<header>
<h1>Article with Metadata</h1>
<p class="byline">By John Doe</p>
<time datetime="2023-01-01">January 1, 2023</time>
</header>
<p>Main article content goes here.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/article-with-metadata",
});
expect(result.content).toContain("# Article with Metadata");
expect(result.content).toContain("**Source:** https://example.com/article-with-metadata");
});
it("should handle code blocks properly", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<article>
<h1>Code Example</h1>
<p>Here's some code:</p>
<pre><code class="language-javascript">
function hello() {
console.log("Hello, world!");
}
</code></pre>
<p>And some inline <code>code</code> too.</p>
</article>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/code-example",
});
expect(result.content).toContain("```");
expect(result.content).toContain("function hello()");
expect(result.content).toContain("`code`");
});
it("should handle HTTP errors", async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: "Not Found",
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://example.com/not-found",
})).rejects.toThrow("HTTP 404: Not Found");
});
it("should handle non-HTML content", async () => {
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("application/json"),
},
text: vi.fn().mockResolvedValue('{"data": "json"}'),
};
mockFetch.mockResolvedValue(mockResponse);
await expect(tool.execute({
url: "https://api.example.com/data.json",
})).rejects.toThrow("Expected HTML content, but received: application/json");
});
it("should handle network errors", async () => {
mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
await expect(tool.execute({
url: "https://example.com",
})).rejects.toThrow("Network error: Unable to fetch https://example.com");
});
it("should handle pages with minimal content", async () => {
const mockHtml = `
<!DOCTYPE html>
<html>
<body>
<div class="navigation">Nav content</div>
<div class="footer">Footer content</div>
</body>
</html>
`;
const mockResponse = {
ok: true,
headers: {
get: vi.fn().mockReturnValue("text/html"),
},
text: vi.fn().mockResolvedValue(mockHtml),
};
mockFetch.mockResolvedValue(mockResponse);
const result = await tool.execute({
url: "https://example.com/minimal-content",
});
expect(result.content).toContain("# Untitled");
expect(result.content).toContain("**Source:** https://example.com/minimal-content");
});
it("should handle invalid URLs", async () => {
await expect(tool.execute({
url: "invalid-url",
})).rejects.toThrow("Failed to read webpage invalid-url");
});
});
});
-123
View File
@@ -1,123 +0,0 @@
import { Readability } from "@mozilla/readability";
import TurndownService from "turndown";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
interface ReadWebpageParams {
url: string;
}
export class ReadWebpageTool implements Tool<ReadWebpageParams> {
private domParser: DOMParser;
private turndownService: TurndownService;
readonly description = "Read and extract the main content from a webpage, converting it to markdown";
readonly inputSchema = z.object({
url: z.string().url().describe(
"The URL of the webpage to read and extract content from"
),
});
constructor(domParser: DOMParser) {
this.domParser = domParser;
this.turndownService = new TurndownService({
headingStyle: "atx",
codeBlockStyle: "fenced",
fence: "```",
emDelimiter: "*",
strongDelimiter: "**",
linkStyle: "inlined",
linkReferenceStyle: "full",
});
// Configure turndown to preserve code blocks and improve formatting
this.turndownService.addRule("preserveCodeBlocks", {
filter: ["pre"],
replacement: (content, node) => {
const codeElement = node.querySelector("code");
if (codeElement) {
const language = codeElement.className.match(/language-(\w+)/)?.[1] || "";
return `\n\n\`\`\`${language}\n${content}\n\`\`\`\n\n`;
}
return `\n\n\`\`\`\n${content}\n\`\`\`\n\n`;
},
});
// Improve table handling
this.turndownService.addRule("tables", {
filter: "table",
replacement: (content) => {
return `\n\n${content}\n\n`;
},
});
}
async execute(args: ReadWebpageParams): Promise<ToolResult> {
const { url } = args;
try {
// Validate URL format
new URL(url);
// Fetch the webpage
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("text/html")) {
throw new Error(`Expected HTML content, but received: ${contentType}`);
}
const html = await response.text();
// Parse the HTML
const doc = this.domParser.parseFromString(html, "text/html");
// Use Readability to extract the main content
const reader = new Readability(doc, {
debug: false,
maxElemsToParse: 0, // No limit
nbTopCandidates: 5,
charThreshold: 500,
classesToPreserve: ["highlight", "code", "pre"],
});
const article = reader.parse();
if (!article) {
throw new Error("Could not extract readable content from the webpage");
}
// Convert the extracted HTML content to markdown
const markdown = this.turndownService.turndown(article.content || "");
// Create a formatted result with metadata
const result = [
`# ${article.title || "Untitled"}`,
"",
article.excerpt ? `${article.excerpt}` : "",
article.excerpt ? "" : "",
`**Source:** ${url}`,
article.byline ? `**Author:** ${article.byline}` : "",
article.publishedTime ? `**Published:** ${article.publishedTime}` : "",
"",
"---",
"",
markdown,
].filter(Boolean).join("\n");
return { content: result };
} catch (error) {
if (error instanceof TypeError && error.message.includes("fetch")) {
throw new Error(`Network error: Unable to fetch ${url}. ${error.message}`);
}
throw new Error(`Failed to read webpage ${url}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
+39 -19
View File
@@ -1,7 +1,7 @@
import { z } from 'zod';
import type { Tool, ToolResult } from './Tool';
import type { JSRuntimeFS } from '../JSRuntime';
import { findSkill, readSkillContent } from '../plugins';
import { readSkillContent, type Skill } from '../skills';
interface SkillParams {
name: string;
@@ -9,45 +9,65 @@ interface SkillParams {
export class SkillTool implements Tool<SkillParams> {
private fs: JSRuntimeFS;
private pluginsPath: string;
private projectPath: string;
readonly description = 'Load and execute a skill from the configured plugins or project. Skills are reusable AI workflows that can be invoked by name.';
private availableSkills: Skill[];
readonly description: string;
readonly inputSchema = z.object({
name: z.string().describe('The name of the skill to execute (lowercase alphanumeric with hyphens)'),
name: z.string().describe('The skill identifier from available_skills'),
});
constructor(fs: JSRuntimeFS, pluginsPath: string, projectPath: string) {
/**
* Create a SkillTool instance.
* @param fs - Filesystem instance
* @param availableSkills - List of available skills (should be pre-loaded)
*/
constructor(fs: JSRuntimeFS, availableSkills: Skill[]) {
this.fs = fs;
this.pluginsPath = pluginsPath;
this.projectPath = projectPath;
this.availableSkills = availableSkills;
this.description = this.generateDescription(availableSkills);
}
/**
* Generate description text for SkillTool based on available skills.
*/
private generateDescription(skills: Skill[]): string {
if (skills.length === 0) {
return 'Load a skill to get detailed instructions for a specific task. No skills are currently available.';
}
return [
'Load a skill to get detailed instructions for a specific task.',
'Skills provide specialized knowledge and step-by-step guidance.',
'Use this when a task matches an available skill\'s description.',
'<available_skills>',
...skills.map(skill =>
` <skill>\n <name>${skill.name}</name>\n <description>${skill.description}</description>\n </skill>`
),
'</available_skills>',
].join('\n');
}
async execute(args: SkillParams): Promise<ToolResult> {
const { name } = args;
try {
// Find the skill across all plugins and project
const skill = await findSkill(this.fs, this.pluginsPath, this.projectPath, name);
// Find the skill in the pre-loaded list
const skill = this.availableSkills.find(s => s.name === name);
if (!skill) {
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
const available = this.availableSkills.map(s => s.name).join(', ');
throw new Error(`Skill "${name}" not found. Available skills: ${available || 'none'}`);
}
// Read and return the skill content
const content = await readSkillContent(this.fs, skill);
return {
content: `# Skill: ${skill.name}
content: `## Skill: ${skill.name}
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
**Description**: ${skill.description}
**Path**: ${skill.path}
**Base directory**: ${skill.path}
---
${content}`
${content.trim()}`
};
} catch (error) {
if (error instanceof Error) {
@@ -1,168 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorStrReplaceTool } from './TextEditorStrReplaceTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Simple mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
this.dirs.add('/project');
this.dirs.add('/project/src');
this.files.set('/project/src/test.ts', 'const message = "hello world";\nconsole.log(message);');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
if (this.dirs.has(path)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(path)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(path)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
// Helper method to get file content
getFileContent(path: string): string | undefined {
return this.files.get(path);
}
}
describe('TextEditorStrReplaceTool', () => {
let mockFS: MockFS;
let tool: TextEditorStrReplaceTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorStrReplaceTool(mockFS, '/project');
});
it('should replace string in file successfully', async () => {
const result = await tool.execute({
path: 'src/test.ts',
old_str: 'hello world',
new_str: 'hello universe'
});
expect(result.content).toContain('String successfully replaced in src/test.ts');
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('hello universe');
expect(mockFS.getFileContent('/project/src/test.ts')).not.toContain('hello world');
});
it('should handle string not found', async () => {
await expect(tool.execute({
path: 'src/test.ts',
old_str: 'nonexistent string',
new_str: 'replacement'
})).rejects.toThrow('The string to replace was not found in src/test.ts');
});
it('should reject absolute paths with helpful error message', async () => {
await expect(tool.execute({
path: '/absolute/path/test.ts',
old_str: 'old',
new_str: 'new'
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
// First create the file in /tmp/
await mockFS.writeFile('/tmp/temp-file.txt', 'original content');
const result = await tool.execute({
path: '/tmp/temp-file.txt',
old_str: 'original',
new_str: 'modified'
});
expect(result.content).toContain('String successfully replaced');
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content');
});
it('should handle whitespace normalization', async () => {
const result = await tool.execute({
path: 'src/test.ts',
old_str: 'const message = "hello world";',
new_str: 'const greeting = "hello universe";',
normalize_whitespace: true
});
expect(result.content).toContain('String successfully replaced');
expect(mockFS.getFileContent('/project/src/test.ts')).toContain('const greeting = "hello universe";');
});
});
-192
View File
@@ -1,192 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface TextEditorStrReplaceParams {
path: string;
old_str: string;
new_str: string;
normalize_whitespace?: boolean;
}
export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
readonly description = "Replace a string in a file with a new string";
readonly inputSchema = z.object({
path: z.string().describe('Path to the file, eg "src/index.ts"'),
old_str: z.string().describe("The string to replace"),
new_str: z.string().describe("The new string to insert"),
normalize_whitespace: z.boolean().optional().describe(
"If true, normalize whitespace and line endings for more flexible matching (default: true)"
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorStrReplaceParams): Promise<ToolResult> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
if (
path === "package.json" || path.endsWith("/package.json") ||
path.endsWith("\\package.json")
) {
const depKeys = [
'"dependencies"',
'"devDependencies"',
'"peerDependencies"',
'"optionalDependencies"',
];
if (
depKeys.some((key) =>
old_str.includes(key) || new_str.includes(key)
)
) {
throw new Error(`🔒 Direct edits to dependencies in package.json are disallowed.\n👉 Please use npm_add_package or npm_remove_package tools for these changes.`);
}
}
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
const content = await this.fs.readFile(absolutePath, "utf8");
// Helper function to normalize whitespace
const normalizeWhitespace = (str: string): string => {
return str
.replace(/\r\n/g, '\n') // Convert CRLF to LF
.replace(/\r/g, '\n') // Convert CR to LF
.split('\n')
.map(line => line.trimEnd()) // Remove trailing whitespace from each line
.join('\n');
};
let searchContent = content;
let searchOldStr = old_str;
let searchNewStr = new_str;
if (normalize_whitespace) {
searchContent = normalizeWhitespace(content);
searchOldStr = normalizeWhitespace(old_str);
searchNewStr = normalizeWhitespace(new_str);
}
if (!searchContent.includes(searchOldStr)) {
// Try to provide helpful debugging information
const lines = searchContent.split('\n');
const oldLines = searchOldStr.split('\n');
// Find potential matches by looking for the first line of old_str
const firstLine = oldLines[0];
const matchingLineNumbers: number[] = [];
if (firstLine) {
lines.forEach((line, index) => {
if (line.includes(firstLine)) {
matchingLineNumbers.push(index + 1);
}
});
}
let errorMessage = `Error: The string to replace was not found in ${path}`;
if (matchingLineNumbers.length > 0) {
errorMessage += `\n\nPossible matches found at lines: ${matchingLineNumbers.join(', ')}`;
// Show context around the first potential match
const firstMatch = matchingLineNumbers[0]! - 1;
const contextStart = Math.max(0, firstMatch - 2);
const contextEnd = Math.min(lines.length, firstMatch + oldLines.length + 2);
const contextLines = lines.slice(contextStart, contextEnd);
errorMessage += `\n\nContext around line ${matchingLineNumbers[0]}:`;
contextLines.forEach((line, index) => {
const lineNum = contextStart + index + 1;
const marker = lineNum === matchingLineNumbers[0] ? '→ ' : ' ';
errorMessage += `\n${marker}${lineNum}: ${line}`;
});
}
if (normalize_whitespace) {
errorMessage += `\n\nNote: Whitespace normalization was applied. Try setting normalize_whitespace to false if the replacement still fails.`;
}
throw new Error(errorMessage);
}
// Count occurrences (simple string counting)
let occurrences = 0;
let pos = 0;
while ((pos = searchContent.indexOf(searchOldStr, pos)) !== -1) {
occurrences++;
pos += searchOldStr.length;
}
// Perform the replacement
let newContent: string;
if (normalize_whitespace) {
// Apply the replacement to the normalized content, then restore original line endings
const normalizedResult = searchContent.replace(searchOldStr, searchNewStr);
// Try to preserve the original line ending style
const hasCarriageReturn = content.includes('\r');
if (hasCarriageReturn) {
if (content.includes('\r\n')) {
// Original had CRLF
newContent = normalizedResult.replace(/\n/g, '\r\n');
} else {
// Original had CR only
newContent = normalizedResult.replace(/\n/g, '\r');
}
} else {
// Original had LF only
newContent = normalizedResult;
}
} else {
newContent = content.replace(old_str, new_str);
}
await this.fs.writeFile(absolutePath, newContent, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(path);
}
let successMessage = `String successfully replaced in ${path}`;
if (occurrences > 1) {
successMessage += ` (${occurrences} occurrences found, only first occurrence replaced)`;
}
return { content: successMessage };
} catch (error) {
throw new Error(String(error));
}
}
}
-335
View File
@@ -1,335 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorViewTool } from './TextEditorViewTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
// Set up a basic project structure
this.dirs.add('/projects');
this.dirs.add('/projects/project1');
this.dirs.add('/projects/project1/src');
this.dirs.add('/projects/project1/.git');
this.dirs.add('/projects/project2');
this.dirs.add('/projects/project2/src');
this.dirs.add('/project');
this.dirs.add('/project/.git');
this.dirs.add('/project/src');
this.dirs.add('/project/node_modules');
this.dirs.add('/tmp');
this.files.set('/projects/project1/package.json', '{"name": "project1"}');
this.files.set('/projects/project1/src/index.ts', 'console.log("project1");');
this.files.set('/projects/project1/.git/config', '[core]\nrepositoryformatversion = 0');
this.files.set('/projects/project1/.git/HEAD', 'ref: refs/heads/main');
this.files.set('/projects/project2/package.json', '{"name": "project2"}');
this.files.set('/projects/project2/src/main.ts', 'console.log("project2");');
this.files.set('/project/package.json', '{"name": "test"}');
this.files.set('/project/src/index.ts', 'console.log("hello");');
this.files.set('/project/.gitignore', 'node_modules\n.git\n');
this.files.set('/project/.git/config', '[core]\nrepositoryformatversion = 0');
this.files.set('/project/.git/HEAD', 'ref: refs/heads/main');
this.files.set('/tmp/uploaded-file.txt', 'This is an uploaded file');
// Add binary files for testing
this.files.set('/project/logo.png', 'BINARY_CONTENT_PNG');
this.files.set('/project/document.pdf', 'BINARY_CONTENT_PDF');
this.files.set('/tmp/image.jpg', 'BINARY_CONTENT_JPG');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
// If no encoding specified, return Uint8Array
if (!encoding) {
// For binary files, return mock binary data with null bytes
if (content.startsWith('BINARY_CONTENT')) {
const binaryData = new Uint8Array(100);
binaryData[0] = 0; // Add null byte to make it appear binary
binaryData[1] = 255; // Add some non-printable bytes
binaryData[2] = 0;
// Fill rest with some pattern
for (let i = 3; i < 100; i++) {
binaryData[i] = i % 256;
}
return binaryData;
}
return new TextEncoder().encode(content);
}
return content;
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
// Normalize path by removing trailing slash
const normalizedPath = path.replace(/\/$/, '') || '/';
const entries: string[] = [];
// Find all files and directories that are direct children of this path
for (const filePath of this.files.keys()) {
if (filePath.startsWith(normalizedPath + '/')) {
const relativePath = filePath.slice(normalizedPath.length + 1);
const parts = relativePath.split('/');
if (parts.length === 1) {
entries.push(parts[0]);
}
}
}
for (const dirPath of this.dirs) {
if (dirPath.startsWith(normalizedPath + '/')) {
const relativePath = dirPath.slice(normalizedPath.length + 1);
const parts = relativePath.split('/');
if (parts.length === 1) {
entries.push(parts[0]);
}
}
}
if (options?.withFileTypes) {
return entries.map(name => ({
name,
isDirectory: () => this.dirs.has(`${normalizedPath}/${name}`),
isFile: () => this.files.has(`${normalizedPath}/${name}`)
}));
}
return entries;
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
// Normalize path by removing trailing slash for directories
const normalizedPath = path.replace(/\/$/, '') || '/';
if (this.dirs.has(normalizedPath)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(normalizedPath)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(normalizedPath)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
}
describe('TextEditorViewTool', () => {
let mockFS: MockFS;
let tool: TextEditorViewTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorViewTool(mockFS, '/project');
});
it('should handle viewing current directory', async () => {
const result = await tool.execute({ path: '.' });
expect(result.content).toContain('src/');
expect(result.content).toContain('package.json');
expect(result.content).toContain('.gitignore');
expect(result.content).toContain('.git/'); // .git directory should now be visible
});
it('should handle viewing subdirectory', async () => {
const result = await tool.execute({ path: 'src' });
expect(result.content).toContain('index.ts');
});
it('should handle viewing a file', async () => {
const result = await tool.execute({ path: 'src/index.ts' });
expect(result.content).toBe('console.log("hello");');
});
it('should handle line filtering', async () => {
const result = await tool.execute({
path: 'src/index.ts',
start_line: 1,
end_line: 1
});
expect(result.content).toBe('console.log("hello");');
});
it('should handle absolute paths', async () => {
const result = await tool.execute({ path: '/tmp/uploaded-file.txt' });
expect(result.content).toBe('This is an uploaded file');
});
it('should handle absolute directory paths', async () => {
const result = await tool.execute({ path: '/tmp' });
expect(result.content).toContain('uploaded-file.txt');
});
it('should handle absolute paths with line filtering', async () => {
const result = await tool.execute({
path: '/tmp/uploaded-file.txt',
start_line: 1,
end_line: 1
});
expect(result.content).toBe('This is an uploaded file');
});
it('should detect binary files by extension and show placeholder', async () => {
const result = await tool.execute({ path: 'logo.png' });
expect(result.content).toContain('[Binary file: PNG file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
expect(result.content).not.toContain('BINARY_CONTENT_PNG');
});
it('should detect PDF files as binary', async () => {
const result = await tool.execute({ path: 'document.pdf' });
expect(result.content).toContain('[Binary file: PDF file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
});
it('should detect binary files with absolute paths', async () => {
const result = await tool.execute({ path: '/tmp/image.jpg' });
expect(result.content).toContain('[Binary file: JPG file');
expect(result.content).toContain('This appears to be a binary file and cannot be displayed as text.');
});
it('should show only project directories when viewing /projects', async () => {
const result = await tool.execute({ path: '/projects' });
// Should show the project directories
expect(result.content).toContain('project1/');
expect(result.content).toContain('project2/');
// Should NOT show the contents of the project directories (depth 1 only)
expect(result.content).not.toContain('package.json');
expect(result.content).not.toContain('src/');
expect(result.content).not.toContain('index.ts');
expect(result.content).not.toContain('main.ts');
});
it('should show only project directories when viewing /projects/', async () => {
const result = await tool.execute({ path: '/projects/' });
// Should show the project directories
expect(result.content).toContain('project1/');
expect(result.content).toContain('project2/');
// Should NOT show the contents of the project directories (depth 1 only)
expect(result.content).not.toContain('package.json');
expect(result.content).not.toContain('src/');
expect(result.content).not.toContain('index.ts');
expect(result.content).not.toContain('main.ts');
});
it('should show .git directory but not traverse its contents when viewing project root', async () => {
const result = await tool.execute({ path: '/project' });
// Should show the .git directory
expect(result.content).toContain('.git/');
// Should show "..." under .git instead of its contents
expect(result.content).toContain('...');
// Should NOT show .git file contents
expect(result.content).not.toContain('config');
expect(result.content).not.toContain('HEAD');
expect(result.content).not.toContain('repositoryformatversion');
// Should still show other directory contents normally
expect(result.content).toContain('src/');
expect(result.content).toContain('package.json');
});
it('should show .git contents when explicitly viewing .git directory', async () => {
const result = await tool.execute({ path: '/project/.git' });
// Should show the .git file contents when explicitly requested
expect(result.content).toContain('config');
expect(result.content).toContain('HEAD');
// Should NOT show "..." when explicitly viewing .git
expect(result.content).not.toContain('...');
});
it('should show .git contents when explicitly viewing .git with relative path', async () => {
const result = await tool.execute({ path: '.git' });
// Should show the .git file contents when explicitly requested
expect(result.content).toContain('config');
expect(result.content).toContain('HEAD');
// Should NOT show "..." when explicitly viewing .git
expect(result.content).not.toContain('...');
});
});
-276
View File
@@ -1,276 +0,0 @@
import { join } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
interface TextEditorViewParams {
path: string;
start_line?: number;
end_line?: number;
}
export class TextEditorViewTool implements Tool<TextEditorViewParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
readonly description = "View the contents of a text file or directory";
readonly inputSchema = z.object({
path: z.string().describe(
'Path of the file or directory to view, eg "src/index.ts" or "src/" for relative paths, or "/tmp/file.txt" for absolute paths',
),
start_line: z.number().min(1).optional().describe(
"Starting line number (1-indexed, inclusive). If provided, only show lines from this line onwards.",
),
end_line: z.number().min(1).optional().describe(
"Ending line number (1-indexed, inclusive). If provided, only show lines up to this line.",
),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(args: TextEditorViewParams): Promise<ToolResult> {
const { path, start_line, end_line } = args;
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) {
// It's an absolute path - use it directly
absolutePath = path;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(this.cwd, path);
}
// Check if the path is a directory
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
// Special handling for projects directory - only show project directories, not their contents
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
if (normalizedPath === this.projectsPath) {
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
return { content: tree };
}
// Check if we're starting from a .git directory
const isGitRoot = absolutePath.endsWith('/.git') || absolutePath === '.git';
// If it's a directory, generate a tree-like listing
// Note: start_line and end_line are ignored for directories
const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot);
return { content: tree };
}
// If it's a file, check if it's binary first
if (await this.isBinaryFile(absolutePath)) {
const stats = await this.fs.stat(absolutePath);
const fileSize = this.formatFileSize(stats.size || 0);
const fileExtension = this.getFileExtension(absolutePath);
return {
content: `[Binary file: ${fileExtension.toUpperCase()} file, ${fileSize}]\n\nThis appears to be a binary file and cannot be displayed as text.`
};
}
// If it's a text file, read and return its contents
let content = await this.fs.readFile(absolutePath, "utf8");
// Apply line filtering if start_line or end_line are provided
if (start_line !== undefined || end_line !== undefined) {
const lines = content.split('\n');
// Validate line numbers first
if (start_line !== undefined && start_line < 1) {
throw new Error("Error: start_line must be >= 1");
}
if (end_line !== undefined && end_line < 1) {
throw new Error("Error: end_line must be >= 1");
}
if (start_line !== undefined && end_line !== undefined && start_line > end_line) {
throw new Error("Error: start_line cannot be greater than end_line");
}
if (start_line !== undefined && start_line > lines.length) {
throw new Error(`Error: start_line ${start_line} is beyond the end of the file (${lines.length} lines)`);
}
const startIdx = start_line !== undefined ? start_line - 1 : 0;
const endIdx = end_line !== undefined ? Math.min(lines.length, end_line) : lines.length;
content = lines.slice(startIdx, endIdx).join('\n');
}
return { content };
} catch (error) {
throw new Error(String(error));
}
}
/**
* Generate a tree-like directory listing
*/
private async generateDirectoryTree(
dirPath: string,
prefix: string = "",
maxDepth: number = 3,
currentDepth: number = 0,
isGitRoot: boolean = false,
): Promise<string> {
if (currentDepth >= maxDepth) {
return prefix + "...\n";
}
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
// Sort entries: directories first, then files, both alphabetically
entries.sort((a, b) => {
if (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
let result = "";
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!
const isLastEntry = i === entries.length - 1;
const connector = isLastEntry ? "└── " : "├── ";
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
if (entry.isDirectory()) {
result += prefix + connector + entry.name + "/\n";
// Special handling for .git directories - don't traverse unless we started from .git
if (entry.name === '.git' && !isGitRoot) {
result += nextPrefix + "...\n";
} else {
const subPath = join(dirPath, entry.name);
result += await this.generateDirectoryTree(
subPath,
nextPrefix,
maxDepth,
currentDepth + 1,
isGitRoot,
);
}
} else {
result += prefix + connector + entry.name + "\n";
}
}
return result;
} catch (error) {
return prefix + `[Error reading directory: ${error}]\n`;
}
}
/**
* Check if a file is likely to be binary based on file extension and content sampling
*/
private async isBinaryFile(filePath: string): Promise<boolean> {
// Check file extension first for known binary types
const extension = this.getFileExtension(filePath).toLowerCase();
const binaryExtensions = new Set([
// Images
'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tif', 'webp', 'svg', 'ico', 'avif',
// Videos
'mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', '3gp', 'm4v',
// Audio
'mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus',
// Archives
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'lz4', 'zst',
// Executables
'exe', 'dll', 'so', 'dylib', 'bin', 'app', 'deb', 'rpm', 'msi',
// Documents (binary formats)
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp',
// Fonts
'ttf', 'otf', 'woff', 'woff2', 'eot',
// Other binary formats
'sqlite', 'db', 'sqlite3', 'pyc', 'class', 'jar', 'war', 'ear',
// Development
'node_modules', 'git', 'gitignore', 'lock'
]);
if (binaryExtensions.has(extension)) {
return true;
}
try {
// For files without clear binary extensions, sample the first chunk of content
// Read as Uint8Array to check for null bytes and non-printable characters
const bytes = await this.fs.readFile(filePath);
// Check first 1024 bytes (or entire file if smaller)
const sampleSize = Math.min(1024, bytes.length);
// Count null bytes and non-printable characters
let nullBytes = 0;
let nonPrintableBytes = 0;
for (let i = 0; i < sampleSize; i++) {
const byte = bytes[i];
if (byte === 0) {
nullBytes++;
}
// Consider bytes outside printable ASCII range (except common whitespace)
// Printable ASCII: 32-126, plus tab (9), newline (10), carriage return (13)
if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) {
nonPrintableBytes++;
}
}
// If more than 1% null bytes or more than 30% non-printable, consider it binary
const nullRatio = nullBytes / sampleSize;
const nonPrintableRatio = nonPrintableBytes / sampleSize;
return nullRatio > 0.01 || nonPrintableRatio > 0.3;
} catch {
// If we can't read the file, assume it might be binary
return true;
}
}
/**
* Get file extension from path
*/
private getFileExtension(filePath: string): string {
const lastDotIndex = filePath.lastIndexOf('.');
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
// If there's no dot, or the dot is before the last slash (hidden file), return empty string
if (lastDotIndex === -1 || lastDotIndex < lastSlashIndex) {
return '';
}
return filePath.slice(lastDotIndex + 1);
}
/**
* Format file size in human-readable format
*/
private formatFileSize(bytes: number): string {
if (bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const k = 1024;
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${units[i]}`;
}
};
-154
View File
@@ -1,154 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TextEditorWriteTool } from './TextEditorWriteTool';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
// Simple mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string> = new Map();
private dirs: Set<string> = new Set();
constructor() {
this.dirs.add('/project');
this.dirs.add('/project/src');
}
async readFile(path: string): Promise<Uint8Array>;
async readFile(path: string, options: 'utf8'): Promise<string>;
async readFile(path: string, options: string): Promise<string>;
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
async readFile(path: string, options: { encoding: string }): Promise<string>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
const content = this.files.get(path);
if (content === undefined) {
throw new Error(`File not found: ${path}`);
}
const encoding = typeof options === 'string' ? options : options?.encoding;
return encoding ? content : new TextEncoder().encode(content);
}
async writeFile(path: string, data: string | Uint8Array, _options?: string | { encoding?: string }): Promise<void> {
const content = typeof data === 'string' ? data : new TextDecoder().decode(data);
this.files.set(path, content);
}
async readdir(path: string): Promise<string[]>;
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
return [];
}
async mkdir(path: string, _options?: { recursive?: boolean }): Promise<void> {
this.dirs.add(path);
}
async stat(path: string): Promise<{
isDirectory(): boolean;
isFile(): boolean;
size?: number;
mtimeMs?: number;
}> {
if (this.dirs.has(path)) {
return {
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now()
};
}
if (this.files.has(path)) {
return {
isDirectory: () => false,
isFile: () => true,
size: this.files.get(path)!.length,
mtimeMs: Date.now()
};
}
throw new Error(`Path not found: ${path}`);
}
async lstat(path: string) {
return this.stat(path);
}
async unlink(path: string): Promise<void> {
this.files.delete(path);
}
async rmdir(path: string): Promise<void> {
this.dirs.delete(path);
}
async rename(oldPath: string, newPath: string): Promise<void> {
if (this.files.has(oldPath)) {
this.files.set(newPath, this.files.get(oldPath)!);
this.files.delete(oldPath);
}
}
async readlink(_path: string): Promise<string> {
throw new Error('Symlinks not supported in mock');
}
async symlink(_target: string, _path: string): Promise<void> {
throw new Error('Symlinks not supported in mock');
}
// Helper method to check if file exists
hasFile(path: string): boolean {
return this.files.has(path);
}
// Helper method to get file content
getFileContent(path: string): string | undefined {
return this.files.get(path);
}
}
describe('TextEditorWriteTool', () => {
let mockFS: MockFS;
let tool: TextEditorWriteTool;
beforeEach(() => {
mockFS = new MockFS();
tool = new TextEditorWriteTool(mockFS, '/project');
});
it('should write a file successfully', async () => {
const result = await tool.execute({
path: 'src/test.ts',
file_text: 'console.log("test");'
});
expect(result.content).toContain('File successfully written to src/test.ts');
expect(mockFS.hasFile('/project/src/test.ts')).toBe(true);
expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");');
});
it('should reject absolute paths outside allowed directories', async () => {
await expect(tool.execute({
path: '/absolute/path/test.ts',
file_text: 'test content'
})).rejects.toThrow('Write access denied');
});
it('should allow writes to /tmp/ directory', async () => {
const result = await tool.execute({
path: '/tmp/temp-file.txt',
file_text: 'temporary content'
});
expect(result.content).toContain('File successfully written to /tmp/temp-file.txt');
expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true);
expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content');
});
it('should reject package.json writes', async () => {
await expect(tool.execute({
path: 'package.json',
file_text: '{"name": "test"}'
})).rejects.toThrow('🔒 Direct writes to package.json are disallowed');
});
});
-74
View File
@@ -1,74 +0,0 @@
import { join, dirname } from "path-browserify";
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { isAbsolutePath, isWriteAllowed, createWriteAccessDeniedError } from "../security";
interface TextEditorWriteParams {
path: string;
file_text: string;
}
export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
private onFileChanged?: (filePath: string) => void;
readonly description = "Create or overwrite a file with new content";
readonly inputSchema = z.object({
path: z.string().describe(
'Path of the file to write, eg "src/index.ts"',
),
file_text: z.string().describe("Content to write to the file"),
});
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string; onFileChanged?: (filePath: string) => void }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
this.onFileChanged = options?.onFileChanged;
}
async execute(args: TextEditorWriteParams): Promise<ToolResult> {
const { path, file_text } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
if (
path === "package.json" || path.endsWith("/package.json") ||
path.endsWith("\\package.json")
) {
throw new Error(`🔒 Direct writes to package.json are disallowed.\n👉 Please use \`npm_add_package\` or \`npm_remove_package\` tools instead.`);
}
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (isAbsolutePath(path)) {
absolutePath = path;
} else {
absolutePath = join(this.cwd, path);
}
await this.fs.mkdir(dirname(absolutePath), { recursive: true });
await this.fs.writeFile(absolutePath, file_text, "utf8");
// Notify about file change (for auto-build)
if (this.onFileChanged) {
this.onFileChanged(path);
}
return { content: `File successfully written to ${path}` };
} catch (error) {
throw new Error(String(error));
}
}
}
+143
View File
@@ -0,0 +1,143 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { TodoReadTool } from './TodoReadTool';
import { TodoWriteTool } from './TodoWriteTool';
import { MockFS } from '@/test/MockFS';
import type { JSRuntimeFS } from '../JSRuntime';
describe('TodoReadTool', () => {
let fs: JSRuntimeFS;
let readTool: TodoReadTool;
let writeTool: TodoWriteTool;
const projectId = 'test-project';
beforeEach(() => {
fs = new MockFS() as unknown as JSRuntimeFS;
readTool = new TodoReadTool(fs, projectId);
writeTool = new TodoWriteTool(fs, projectId);
});
it('should have a description', () => {
expect(readTool.description).toBeDefined();
expect(readTool.description.length).toBeGreaterThan(0);
});
it('should have an input schema', () => {
expect(readTool.inputSchema).toBeDefined();
});
it('should return empty message when no todos exist', async () => {
const result = await readTool.execute({});
// Should return empty JSON array
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should read todos from .git/ai/TODO file', async () => {
const todos = [
{
id: '1',
content: 'Test task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Test task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
];
// Write todos first
await writeTool.execute({ todos });
// Read them back
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(1);
expect(completed.length).toBe(1);
});
it('should count active and completed tasks correctly', async () => {
const todos = [
{
id: '1',
content: 'Task 1',
status: 'pending' as const,
priority: 'high' as const,
},
{
id: '2',
content: 'Task 2',
status: 'completed' as const,
priority: 'medium' as const,
},
{
id: '3',
content: 'Task 3',
status: 'in_progress' as const,
priority: 'low' as const,
},
{
id: '4',
content: 'Task 4',
status: 'cancelled' as const,
priority: 'low' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const resultData = JSON.parse(result.content);
expect(resultData).toEqual(todos);
// Verify counts
const active = resultData.filter((x: { status: string }) => x.status !== 'completed' && x.status !== 'cancelled');
const completed = resultData.filter((x: { status: string }) => x.status === 'completed');
expect(active.length).toBe(2);
expect(completed.length).toBe(1);
});
it('should handle invalid JSON in TODO file', async () => {
// Write invalid JSON
await fs.mkdir(`/projects/${projectId}/.git/ai`, { recursive: true });
await fs.writeFile(`/projects/${projectId}/.git/ai/TODO`, 'invalid json');
const result = await readTool.execute({});
// Should return empty JSON array when file is invalid
const resultData = JSON.parse(result.content);
expect(resultData).toEqual([]);
});
it('should display full todo information', async () => {
const todos = [
{
id: 'abc123',
content: 'Implement new feature',
status: 'in_progress' as const,
priority: 'high' as const,
},
];
await writeTool.execute({ todos });
const result = await readTool.execute({});
// Should return JSON
const parsed = JSON.parse(result.content);
expect(parsed[0].id).toBe('abc123');
expect(parsed[0].content).toBe('Implement new feature');
expect(parsed[0].status).toBe('in_progress');
expect(parsed[0].priority).toBe('high');
});
});
+46
View File
@@ -0,0 +1,46 @@
import { z } from "zod";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import type { TodoInfo } from "./TodoWriteTool";
import { join } from "path-browserify";
type TodoReadParams = Record<string, never>;
export class TodoReadTool implements Tool<TodoReadParams> {
private fs: JSRuntimeFS;
private projectId: string;
private projectsPath: string;
readonly description = "Use this tool to read your todo list";
readonly inputSchema = z.object({});
constructor(fs: JSRuntimeFS, projectId: string, options?: { projectsPath?: string }) {
this.fs = fs;
this.projectId = projectId;
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(_args: TodoReadParams): Promise<ToolResult> {
try {
// Read todos from .git/ai/TODO file
const todoPath = join(this.projectsPath, this.projectId, ".git", "ai", "TODO");
let todos: TodoInfo[] = [];
try {
const content = await this.fs.readFile(todoPath, "utf8");
todos = JSON.parse(content);
} catch {
// File doesn't exist or is invalid - return empty array
todos = [];
}
return {
content: JSON.stringify(todos, null, 2),
};
} catch (error) {
throw new Error(`Failed to read todos: ${String(error)}`);
}
}
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more