From eabba1ececf6a3f6a08c82c7d11c86ff22fd3e4d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 13 Nov 2025 18:12:45 -0600 Subject: [PATCH] Expose full config and defaultConfig to systemPrompt template --- src/components/SessionManagerProvider.tsx | 72 +++++++++++++++++---- src/lib/SessionManager.test.ts | 32 +++++++++- src/lib/SessionManager.ts | 65 +++++++++++-------- src/lib/system.test.ts | 62 ++++++++++++------ src/lib/system.ts | 78 +++++++++++++---------- 5 files changed, 215 insertions(+), 94 deletions(-) diff --git a/src/components/SessionManagerProvider.tsx b/src/components/SessionManagerProvider.tsx index cd9eefca..839223de 100644 --- a/src/components/SessionManagerProvider.tsx +++ b/src/components/SessionManagerProvider.tsx @@ -1,8 +1,7 @@ -import { ReactNode, useMemo, useEffect } from 'react'; +import { ReactNode, useEffect, useRef } from 'react'; import { SessionManagerContext } from '@/contexts/SessionManagerContext'; import { SessionManager } from '@/lib/SessionManager'; import { useFS } from '@/hooks/useFS'; -import { useFSPaths } from '@/hooks/useFSPaths'; import { useAISettings } from '@/hooks/useAISettings'; import { useProviderModels } from '@/hooks/useProviderModels'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -18,31 +17,80 @@ interface SessionManagerProviderProps { */ export function SessionManagerProvider({ children }: SessionManagerProviderProps) { const { fs } = useFS(); - const { projectsPath, pluginsPath } = useFSPaths(); const { settings } = useAISettings(); const { models } = useProviderModels(); const { user, metadata } = useCurrentUser(); - const { config } = useAppContext(); + const { config, defaultConfig } = useAppContext(); const { nostr } = useNostr(); - const sessionManager = useMemo(() => { - const getProviderModels = () => models; - const getCurrentUser = () => ({ user, metadata }); - return new SessionManager(fs, nostr, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath, config.systemPrompt); - }, [fs, nostr, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath, config.systemPrompt]); + // Create SessionManager instance only once + const sessionManager = useRef(undefined); + + // Use refs so SessionManager always has the latest data + const configRef = useRef(config); + const defaultConfigRef = useRef(defaultConfig); + const settingsRef = useRef(settings); + const modelsRef = useRef(models); + const userRef = useRef(user); + const metadataRef = useRef(metadata); + + // Update refs when values change + useEffect(() => { + configRef.current = config; + }, [config]); + + useEffect(() => { + defaultConfigRef.current = defaultConfig; + }, [defaultConfig]); + + useEffect(() => { + settingsRef.current = settings; + }, [settings]); + + useEffect(() => { + modelsRef.current = models; + }, [models]); + + useEffect(() => { + userRef.current = user; + }, [user]); + + useEffect(() => { + metadataRef.current = metadata; + }, [metadata]); + + // Initialize SessionManager only once + if (!sessionManager.current) { + // Callbacks access refs to get latest values + const getProviderModels = () => modelsRef.current; + const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current }); + const getConfig = () => configRef.current; + const getDefaultConfig = () => defaultConfigRef.current; + const getSettings = () => settingsRef.current; + + sessionManager.current = new SessionManager( + fs, + nostr, + getSettings, + getConfig, + getDefaultConfig, + getProviderModels, + getCurrentUser, + ); + } // Cleanup on unmount useEffect(() => { return () => { // Fire and forget cleanup - we don't need to await in useEffect cleanup - sessionManager.cleanup().catch(error => { + sessionManager.current?.cleanup().catch(error => { console.warn('Failed to cleanup session manager:', error); }); }; - }, [sessionManager]); + }, []); return ( - + {children} ); diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index ceb92149..ee15cf3b 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SessionManager, type AIMessage } from './SessionManager'; import type { JSRuntimeFS } from './JSRuntime'; import type { NPool } from '@nostrify/nostrify'; +import type { AppConfig } from '@/contexts/AppContext'; // Mock the filesystem const mockFS: JSRuntimeFS = { @@ -30,6 +31,32 @@ const mockNostr: NPool = { event: vi.fn(), } as unknown as NPool; +// Test configuration +const testConfig: AppConfig = { + theme: 'light', + relayMetadata: { + relays: [ + { url: 'wss://relay.nostr.band', read: true, write: true }, + ], + updatedAt: 0, + }, + projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git', + esmUrl: 'https://esm.shakespeare.diy', + corsProxy: 'https://proxy.shakespeare.diy/?url={href}', + faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', + previewDomain: 'local-shakespeare.dev', + language: 'en', + showcaseEnabled: true, + showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', + ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + fsPathPlugins: '/plugins', + sentryDsn: '', + sentryEnabled: false, +}; + describe('SessionManager', () => { let sessionManager: SessionManager; const mockAISettings = { @@ -43,7 +70,10 @@ describe('SessionManager', () => { }; beforeEach(() => { - sessionManager = new SessionManager(mockFS, mockNostr, mockAISettings); + const getSettings = () => mockAISettings; + const getConfig = () => testConfig; + const getDefaultConfig = () => testConfig; + sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig); }); it('should initialize streaming message with reasoning content', async () => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index e1ddcc6e..f32a8d4b 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -13,6 +13,7 @@ import { EmptyMessageError } from './errors/EmptyMessageError'; import { isEmptyMessage } from './isEmptyMessage'; import { Git } from './git'; import type { NPool } from '@nostrify/nostrify'; +import type { AppConfig } from '@/contexts/AppContext'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -60,35 +61,34 @@ export class SessionManager { private sessions = new Map(); private listeners: Partial void>>> = {}; private fs: JSRuntimeFS; - private git: Git; - private aiSettings: { providers: AIProvider[] }; + private nostr: NPool; + private getSettings: () => { providers: AIProvider[] }; + private getConfig: () => AppConfig; + private getDefaultConfig: () => AppConfig; private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }; - private corsProxy?: string; - private projectsPath: string; - private pluginsPath?: string; - private systemPromptTemplate?: string; constructor( fs: JSRuntimeFS, nostr: NPool, - aiSettings: { providers: AIProvider[] }, + getSettings: () => { providers: AIProvider[] }, + getConfig: () => AppConfig, + getDefaultConfig: () => AppConfig, getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>, getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }, - corsProxy?: string, - projectsPath = '/projects', - pluginsPath?: string, - systemPromptTemplate?: string, ) { this.fs = fs; - this.git = new Git({ fs, nostr, corsProxy }); - this.aiSettings = aiSettings; + this.nostr = nostr; + this.getSettings = getSettings; + this.getConfig = getConfig; + this.getDefaultConfig = getDefaultConfig; this.getProviderModels = getProviderModels; this.getCurrentUser = getCurrentUser; - this.projectsPath = projectsPath; - this.pluginsPath = pluginsPath; - this.corsProxy = corsProxy; - this.systemPromptTemplate = systemPromptTemplate; + } + + private get git(): Git { + const config = this.getConfig(); + return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy }); } /** @@ -105,7 +105,8 @@ export class SessionManager { // Try to load existing history try { - const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`); + const config = this.getConfig(); + const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`); const lastSession = await dotAI.readLastSessionHistory(); if (lastSession) { messages = lastSession.messages; @@ -217,14 +218,19 @@ export class SessionManager { this.emit('loadingChanged', projectId, true); try { + // Get latest config and settings + const config = this.getConfig(); + const defaultConfig = this.getDefaultConfig(); + const settings = this.getSettings(); + // Parse provider and model - const parsed = parseProviderModel(providerModel, this.aiSettings.providers); + const parsed = parseProviderModel(providerModel, settings.providers); const provider = parsed.provider; const model = parsed.model; // Initialize OpenAI client const { user, metadata } = this.getCurrentUser?.() ?? {}; - const openai = createAIClient(provider, user, this.corsProxy); + const openai = createAIClient(provider, user, config.corsProxy); let stepCount = 0; const maxSteps = session.maxSteps || 50; @@ -249,23 +255,23 @@ export class SessionManager { // Get repository URL if available let repositoryUrl: string | undefined; try { - const remoteUrl = await this.git.getRemoteURL(`${this.projectsPath}/${projectId}`, 'origin'); + const remoteUrl = await this.git.getRemoteURL(`${config.fsPathProjects}/${projectId}`, 'origin'); repositoryUrl = remoteUrl || undefined; } catch { // No repository URL available } const systemPrompt = await makeSystemPrompt({ - cwd: `${this.projectsPath}/${projectId}`, + cwd: `${config.fsPathProjects}/${projectId}`, fs: this.fs, mode: "agent", tools: Object.values(session.tools), - pluginsPath: this.pluginsPath, + config, + defaultConfig, user, metadata, - corsProxy: this.corsProxy, repositoryUrl, - template: this.systemPromptTemplate, + template: config.systemPrompt, }); // Prepare messages for AI @@ -560,7 +566,8 @@ export class SessionManager { // Otherwise, get the cost from the models endpoint try { - const parsed = parseProviderModel(providerModel, this.aiSettings.providers); + const settings = this.getSettings(); + const parsed = parseProviderModel(providerModel, settings.providers); const modelName = parsed.model; const provider = parsed.provider; @@ -600,7 +607,8 @@ export class SessionManager { if (!session) return; try { - const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`); + const config = this.getConfig(); + const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`); await dotAI.setHistory(session.sessionName, session.messages); } catch (error) { console.warn('Failed to save session history:', error); @@ -612,7 +620,8 @@ export class SessionManager { */ private async accumulateProjectCost(projectId: string, requestCost: number): Promise { try { - const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`); + const config = this.getConfig(); + const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`); // Read current project total const currentTotal = await dotAI.readCost(); diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index 54c327c0..bb4fcd27 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -3,6 +3,7 @@ import { makeSystemPrompt, MakeSystemPromptOpts } from './system'; import { JSRuntimeFS } from './JSRuntime'; import { NUser } from '@nostrify/react/login'; import { NostrMetadata } from '@nostrify/nostrify'; +import { AppConfig } from '@/contexts/AppContext'; import OpenAI from 'openai'; // Mock the plugins module @@ -17,6 +18,32 @@ vi.mock('path-browserify', () => ({ import { getAllSkills } from './plugins'; +// Test configuration +const testConfig: AppConfig = { + theme: 'light', + relayMetadata: { + relays: [ + { url: 'wss://relay.nostr.band', read: true, write: true }, + ], + updatedAt: 0, + }, + projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git', + esmUrl: 'https://esm.shakespeare.diy', + corsProxy: 'https://proxy.shakespeare.diy/?url={href}', + faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico', + previewDomain: 'local-shakespeare.dev', + language: 'en', + showcaseEnabled: true, + showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc', + ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'], + fsPathProjects: '/projects', + fsPathConfig: '/config', + fsPathTmp: '/tmp', + fsPathPlugins: '/plugins', + sentryDsn: '', + sentryEnabled: false, +}; + describe('makeSystemPrompt', () => { let mockFs: JSRuntimeFS; let baseOpts: MakeSystemPromptOpts; @@ -43,6 +70,8 @@ describe('makeSystemPrompt', () => { mode: 'agent', fs: mockFs, cwd: '/projects/test-project', + config: testConfig, + defaultConfig: testConfig, }; // Mock getAllSkills to return empty array by default @@ -207,7 +236,10 @@ describe('makeSystemPrompt', () => { describe('skills section', () => { it('should show no skills message when pluginsPath is not provided', async () => { - const result = await makeSystemPrompt(baseOpts); + const result = await makeSystemPrompt({ + ...baseOpts, + config: { ...testConfig, fsPathPlugins: '' }, + }); expect(result).toContain('## Skills'); expect(result).toContain('No skills are currently configured'); @@ -216,10 +248,7 @@ describe('makeSystemPrompt', () => { it('should show no skills message when getAllSkills returns empty array', async () => { vi.mocked(getAllSkills).mockResolvedValue([]); - const result = await makeSystemPrompt({ - ...baseOpts, - pluginsPath: '/plugins', - }); + const result = await makeSystemPrompt(baseOpts); expect(result).toContain('No skills are currently configured'); expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins'); @@ -241,10 +270,7 @@ describe('makeSystemPrompt', () => { }, ]); - const result = await makeSystemPrompt({ - ...baseOpts, - pluginsPath: '/plugins', - }); + const result = await makeSystemPrompt(baseOpts); expect(result).toContain('## Skills'); expect(result).toContain('**create_component**: Create a new React component'); @@ -256,10 +282,7 @@ describe('makeSystemPrompt', () => { it('should handle getAllSkills errors gracefully', async () => { vi.mocked(getAllSkills).mockRejectedValue(new Error('Plugin error')); - const result = await makeSystemPrompt({ - ...baseOpts, - pluginsPath: '/plugins', - }); + const result = await makeSystemPrompt(baseOpts); expect(result).toContain('No skills are currently configured'); }); @@ -267,19 +290,19 @@ describe('makeSystemPrompt', () => { describe('CORS proxy section', () => { it('should not include CORS proxy section when not provided', async () => { - const result = await makeSystemPrompt(baseOpts); + const result = await makeSystemPrompt({ + ...baseOpts, + config: { ...testConfig, corsProxy: '' }, + }); expect(result).not.toContain('## Working Around CORS Issues'); }); it('should include CORS proxy information when provided', async () => { - const result = await makeSystemPrompt({ - ...baseOpts, - corsProxy: 'https://cors-proxy.example.com/{href}', - }); + const result = await makeSystemPrompt(baseOpts); expect(result).toContain('## Working Around CORS Issues'); - expect(result).toContain('**CORS Proxy URL Template**: `https://cors-proxy.example.com/{href}`'); + expect(result).toContain('**CORS Proxy URL Template**: `https://proxy.shakespeare.diy/?url={href}`'); }); }); @@ -391,7 +414,6 @@ describe('makeSystemPrompt', () => { const result = await makeSystemPrompt({ ...baseOpts, user, - corsProxy: 'https://cors.example.com/{href}', repositoryUrl: 'https://github.com/test/repo.git', }); diff --git a/src/lib/system.ts b/src/lib/system.ts index 9eb35298..a33902c7 100644 --- a/src/lib/system.ts +++ b/src/lib/system.ts @@ -6,16 +6,17 @@ import { nip19 } from "nostr-tools"; import { Eta } from "eta"; import { JSRuntimeFS } from "./JSRuntime"; import { getAllSkills } from "./plugins"; +import type { AppConfig } from "@/contexts/AppContext"; export interface MakeSystemPromptOpts { tools: OpenAI.Chat.Completions.ChatCompletionTool[]; mode: "init" | "agent"; fs: JSRuntimeFS; cwd: string; - pluginsPath?: string; + config: AppConfig; + defaultConfig: AppConfig; user?: NUser; metadata?: NostrMetadata; - corsProxy?: string; repositoryUrl?: string; template?: string; } @@ -54,14 +55,14 @@ Shakespeare is a web-based development environment where users can build Nostr w <% if (ctx.user) { %>The user is logged into Nostr with the following profile: - **Nostr pubkey (hex)**: <%= ctx.user.pubkey %> -- **Nostr npub**: <%= ctx.npub %><% if (ctx.metadata?.name) { %> -- **Name**: <%= ctx.metadata.name %><% } %><% if (ctx.metadata?.about) { %> -- **About**: <%= ctx.sanitizeNewlines(ctx.metadata.about) %><% } %><% if (ctx.metadata?.website) { %> -- **Website**: <%= ctx.metadata.website %><% } %><% if (ctx.metadata?.picture) { %> -- **Avatar**: <%= ctx.metadata.picture %><% } %><% if (ctx.metadata?.banner) { %> -- **Banner**: <%= ctx.metadata.banner %><% } %><% if (ctx.metadata?.nip05) { %> -- **NIP-05**: <%= ctx.metadata.nip05 %><% } %><% if (ctx.metadata?.lud16) { %> -- **Lightning Address**: <%= ctx.metadata.lud16 %><% } %> +- **Nostr npub**: <%= ctx.user.npub %><% if (ctx.user.name) { %> +- **Name**: <%= ctx.user.name %><% } %><% if (ctx.user.about) { %> +- **About**: <%= ctx.user.about %><% } %><% if (ctx.user.website) { %> +- **Website**: <%= ctx.user.website %><% } %><% if (ctx.user.picture) { %> +- **Avatar**: <%= ctx.user.picture %><% } %><% if (ctx.user.banner) { %> +- **Banner**: <%= ctx.user.banner %><% } %><% if (ctx.user.nip05) { %> +- **NIP-05**: <%= ctx.user.nip05 %><% } %><% if (ctx.user.lud16) { %> +- **Lightning Address**: <%= ctx.user.lud16 %><% } %> Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.<% } else { %>The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.<% } %> @@ -123,8 +124,8 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a ├── config/ # Configuration files │ ├── ai.json # AI provider settings and API keys │ └── git.json # Git credentials and repository settings -└── tmp/ # Temporary files and scratch space - └── ... # Various temporary files and directories +└── tmp/ # Temporary files and scratch space + └── ... # Various temporary files and directories \`\`\` ### Key VFS Features @@ -158,7 +159,7 @@ You have access to the following tools: ## Skills -<% if (ctx.skills && ctx.skills.length > 0) { %>You have access to the following skills. **Skills MUST be used whenever applicable** by calling the <%= ctx.backtick %>skill<%= ctx.backtick %> tool with the skill name. +<% if (ctx.skills && ctx.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: <% ctx.skills.forEach(function(skill) { %> @@ -169,15 +170,15 @@ Available skills: **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.<% } %> -Users can configure skills in Settings > AI (<%= ctx.originUrl %>/settings/ai) by adding plugins that contain skills.<% if (ctx.corsProxy) { %> +Users can configure skills in Settings > AI (<%= ctx.location.origin %>/settings/ai) by adding plugins that contain skills.<% if (ctx.config.corsProxy) { %> ## Working Around CORS Issues If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy: -**CORS Proxy URL Template**: <%= ctx.backtick %><%= ctx.corsProxy %><%= ctx.backtick %> +**CORS Proxy URL Template**: \`<%= ctx.config.corsProxy %>\` -Replace <%= ctx.backtick %>{href}<%= ctx.backtick %>, <%= ctx.backtick %>{hostname}<%= ctx.backtick %>, or other URL components in the template as needed.<% } %> +Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.<% } %> ## Edit with Shakespeare @@ -197,16 +198,16 @@ This project has a repository URL configured, so you can create an "Edit with Sh \`\`\` -Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use <%= ctx.backtick %>height: auto<%= ctx.backtick %> in CSS (or <%= ctx.backtick %>"h-auto"<%= ctx.backtick %> in Tailwind CSS) when applicable.<% } else { %> +Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.<% } else { %> **Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.<% } %><% if (ctx.readmeText) { %> <%= ctx.readmeText %><% } %><% if (ctx.agentText) { %> -<%= ctx.agentText %><% } %>`; +<%= ctx.agentsText %><% } %>`; export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise { - const { tools, mode, fs, cwd, pluginsPath, user, metadata, corsProxy, repositoryUrl, template } = opts; + const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts; // Add current date const currentDate = new Date().toLocaleDateString("en-US", { @@ -218,9 +219,9 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise = []; - if (pluginsPath) { + if (config.fsPathPlugins) { try { - skills = await getAllSkills(fs, pluginsPath); + skills = await getAllSkills(fs, config.fsPathPlugins); } catch { // Skills not available, use empty array skills = []; @@ -237,10 +238,10 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise text.replace(/[\r\n]+/g, ' '), - // Helper function to output backticks - backtick: '`', + agentsText, }; // Render the template with the context