diff --git a/.github/workflows/electron-build.yml b/.github/workflows/electron-build.yml index 6566f105..ec60096f 100644 --- a/.github/workflows/electron-build.yml +++ b/.github/workflows/electron-build.yml @@ -23,7 +23,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v6 with: - node-version: 24 + node-version: 24.15.0 cache: 'pnpm' cache-dependency-path: 'apps/x/pnpm-lock.yaml' @@ -111,6 +111,7 @@ jobs: with: name: distributables path: apps/x/apps/main/out/make/* + if-no-files-found: error retention-days: 30 build-linux: @@ -128,7 +129,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v6 with: - node-version: 24 + node-version: 24.15.0 cache: 'pnpm' cache-dependency-path: 'apps/x/pnpm-lock.yaml' @@ -175,6 +176,7 @@ jobs: with: name: distributables-linux path: apps/x/apps/main/out/make/* + if-no-files-found: error retention-days: 30 build-windows: @@ -192,7 +194,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v6 with: - node-version: 24 + node-version: 24.15.0 cache: 'pnpm' cache-dependency-path: 'apps/x/pnpm-lock.yaml' @@ -241,4 +243,5 @@ jobs: with: name: distributables-windows path: apps/x/apps/main/out/make/* + if-no-files-found: error retention-days: 30 diff --git a/apps/x/ANALYTICS.md b/apps/x/ANALYTICS.md index 572e9a6f..2d9816d0 100644 --- a/apps/x/ANALYTICS.md +++ b/apps/x/ANALYTICS.md @@ -16,6 +16,8 @@ ## Event catalog +All PostHog events include `app_version` automatically. Main-process events add it in `packages/core/src/analytics/posthog.ts`; renderer events get it from the `analytics:bootstrap` IPC payload and an initialization-time `before_send` hook. + ### `llm_usage` Emitted whenever ai-sdk returns token usage (one event per LLM call, not per run). @@ -101,6 +103,7 @@ Persistent across sessions for the same user. Set via `posthog.people.set` or as | `email` | main on identify | From `/v1/me`; powers PostHog cohort match + integrations | | `plan`, `status` | main on identify | Subscription state | | `api_url` | both processes (init + identify) | Distinguishes prod / staging / custom — assign meaning in PostHog dashboard. `https://api.x.rowboatlabs.com` = production | +| `app_version` | both processes (init + identify) | Electron app version; also included automatically on every event | | `signed_in` | renderer | `true` while rowboat OAuth is connected | | `{provider}_connected` | renderer | One of `gmail`, `calendar`, `slack`, `rowboat` | | `total_notes` | renderer (init) | Workspace size signal | diff --git a/apps/x/apps/main/bundle.mjs b/apps/x/apps/main/bundle.mjs index 9ae77e0e..976e8db3 100644 --- a/apps/x/apps/main/bundle.mjs +++ b/apps/x/apps/main/bundle.mjs @@ -10,11 +10,13 @@ */ import * as esbuild from 'esbuild'; +import { readFile } from 'node:fs/promises'; // In CommonJS, import.meta.url doesn't exist. We need to polyfill it. // The banner defines __import_meta_url at the top of the bundle, // and we use define to replace all import.meta.url references with it. const cjsBanner = `var __import_meta_url = require('url').pathToFileURL(__filename).href;`; +const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')); await esbuild.build({ entryPoints: ['./dist/main.js'], @@ -36,6 +38,7 @@ await esbuild.build({ // Empty strings disable analytics gracefully. 'process.env.POSTHOG_KEY': JSON.stringify(process.env.VITE_PUBLIC_POSTHOG_KEY ?? ''), 'process.env.POSTHOG_HOST': JSON.stringify(process.env.VITE_PUBLIC_POSTHOG_HOST ?? 'https://us.i.posthog.com'), + 'process.env.ROWBOAT_APP_VERSION': JSON.stringify(pkg.version ?? ''), }, }); diff --git a/apps/x/apps/main/src/ipc.ts b/apps/x/apps/main/src/ipc.ts index 5f246783..0e3662b6 100644 --- a/apps/x/apps/main/src/ipc.ts +++ b/apps/x/apps/main/src/ipc.ts @@ -1,4 +1,4 @@ -import { ipcMain, BrowserWindow, shell, dialog, systemPreferences, desktopCapturer } from 'electron'; +import { ipcMain, BrowserWindow, shell, dialog, systemPreferences, desktopCapturer, app } from 'electron'; import { ipc } from '@x/shared'; import path from 'node:path'; import os from 'node:os'; @@ -31,6 +31,9 @@ import { listGatewayModels } from '@x/core/dist/models/gateway.js'; import type { IModelConfigRepo } from '@x/core/dist/models/repo.js'; import type { IOAuthRepo } from '@x/core/dist/auth/repo.js'; import { IGranolaConfigRepo } from '@x/core/dist/knowledge/granola/repo.js'; +import { ICodeModeConfigRepo } from '@x/core/dist/code-mode/repo.js'; +import { checkCodeModeAgentStatus } from '@x/core/dist/code-mode/status.js'; +import { invalidateCopilotInstructionsCache } from '@x/core/dist/application/assistant/instructions.js'; import { triggerSync as triggerGranolaSync } from '@x/core/dist/knowledge/granola/sync.js'; import { ISlackConfigRepo } from '@x/core/dist/slack/repo.js'; import { isOnboardingComplete, markOnboardingComplete } from '@x/core/dist/config/note_creation_config.js'; @@ -453,6 +456,7 @@ export function setupIpcHandlers() { return { installationId: getInstallationId(), apiUrl: API_URL, + appVersion: app.getVersion(), }; }, 'workspace:getRoot': async () => { @@ -527,7 +531,7 @@ export function setupIpcHandlers() { return runsCore.createRun(args); }, 'runs:createMessage': async (_event, args) => { - return { messageId: await runsCore.createMessage(args.runId, args.message, args.voiceInput, args.voiceOutput, args.searchEnabled, args.middlePaneContext) }; + return { messageId: await runsCore.createMessage(args.runId, args.message, args.voiceInput, args.voiceOutput, args.searchEnabled, args.middlePaneContext, args.codeMode) }; }, 'runs:authorizePermission': async (_event, args) => { await runsCore.authorizePermission(args.runId, args.authorization); @@ -631,6 +635,20 @@ export function setupIpcHandlers() { const config = await repo.getConfig(); return { enabled: config.enabled }; }, + 'codeMode:getConfig': async () => { + const repo = container.resolve('codeModeConfigRepo'); + const config = await repo.getConfig(); + return { enabled: config.enabled }; + }, + 'codeMode:setConfig': async (_event, args) => { + const repo = container.resolve('codeModeConfigRepo'); + await repo.setConfig({ enabled: args.enabled }); + invalidateCopilotInstructionsCache(); + return { success: true }; + }, + 'codeMode:checkAgentStatus': async () => { + return await checkCodeModeAgentStatus(); + }, 'granola:setConfig': async (_event, args) => { const repo = container.resolve('granolaConfigRepo'); await repo.setConfig({ enabled: args.enabled }); diff --git a/apps/x/apps/main/src/main.ts b/apps/x/apps/main/src/main.ts index ab026fff..81d43553 100644 --- a/apps/x/apps/main/src/main.ts +++ b/apps/x/apps/main/src/main.ts @@ -51,6 +51,7 @@ import { extractDeepLinkFromArgv, setMainWindowForDeepLinks, } from "./deeplink.js"; +import { disconnectGoogleIfScopesStale } from "./oauth-handler.js"; const execAsync = promisify(exec); @@ -351,6 +352,11 @@ app.whenReady().then(async () => { registerConsumer(backgroundTaskEventConsumer); initEventProcessor(); + // If the stored Google grant predates a scope change (only old scopes), + // disconnect it now so the user re-connects with the current scopes before + // any Google sync runs against the stale grant. + await disconnectGoogleIfScopesStale(); + // start gmail sync initGmailSync(); diff --git a/apps/x/apps/main/src/oauth-handler.ts b/apps/x/apps/main/src/oauth-handler.ts index ab00ab8c..1048d9b8 100644 --- a/apps/x/apps/main/src/oauth-handler.ts +++ b/apps/x/apps/main/src/oauth-handler.ts @@ -508,7 +508,7 @@ export async function disconnectProvider(provider: string): Promise<{ success: b if (connection.mode === 'rowboat' && connection.tokens?.access_token) { try { const revokeUrl = `https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(connection.tokens.access_token)}`; - const res = await fetch(revokeUrl, { method: 'POST' }); + const res = await fetch(revokeUrl, { method: 'POST', signal: AbortSignal.timeout(5000) }); if (!res.ok) { console.warn(`[OAuth] Google revoke returned ${res.status}; continuing with local disconnect`); } @@ -532,6 +532,81 @@ export async function disconnectProvider(provider: string): Promise<{ success: b } } +/** + * Startup migration for Google scope changes. When a connected Google grant was + * issued before a scope was added (e.g. old installs on gmail.readonly that + * never received gmail.modify), invalidate it so the user is prompted to + * reconnect and re-grant with the current scopes. The currently-requested + * scopes in the provider config are the source of truth: a grant missing any + * of them is treated as stale. + * + * We revoke + clear the stale token but DELIBERATELY keep the provider entry + * with an `error` set rather than calling disconnectProvider (which deletes the + * whole entry). The renderer's reconnect prompts — the sidebar "Reconnect your + * accounts" alert and the connectors "Reconnect" row — key off this `error` + * field, not off the connected flag. A fully deleted entry has no error and is + * indistinguishable from "never connected", so no prompt would ever appear. + * + * Tokens with no recorded scopes (very old installs that never persisted them) + * are also treated as stale. Safe to call on every startup — it's a no-op once + * the grant covers all current scopes, and once invalidated the early return on + * the missing token keeps it from re-running until the user reconnects. + */ +export async function disconnectGoogleIfScopesStale(): Promise { + try { + const oauthRepo = getOAuthRepo(); + const connection = await oauthRepo.read('google'); + + // Not connected (or already invalidated) — nothing to migrate. + if (!connection.tokens) { + return; + } + + const providerConfig = await getProviderConfig('google'); + const requiredScopes = providerConfig.scopes ?? []; + if (requiredScopes.length === 0) { + return; + } + + const granted = new Set(connection.tokens.scopes ?? []); + const missingScopes = requiredScopes.filter((scope) => !granted.has(scope)); + if (missingScopes.length === 0) { + return; + } + + console.log( + `[OAuth] Google grant is missing current scopes [${missingScopes.join(', ')}]; ` + + 'invalidating it so the user is prompted to reconnect with the new scopes.' + ); + + // Best-effort revoke at Google for rowboat-mode grants (mirrors disconnectProvider). + if (connection.mode === 'rowboat' && connection.tokens.access_token) { + try { + const revokeUrl = `https://oauth2.googleapis.com/revoke?token=${encodeURIComponent(connection.tokens.access_token)}`; + const res = await fetch(revokeUrl, { method: 'POST', signal: AbortSignal.timeout(5000) }); + if (!res.ok) { + console.warn(`[OAuth] Google revoke returned ${res.status}; continuing with local invalidation`); + } + } catch (error) { + console.warn('[OAuth] Google revoke failed; continuing with local invalidation:', error); + } + } + + // Drop the stale token but keep the entry with an error so the reconnect + // prompt fires (see the note above). + await oauthRepo.upsert('google', { + tokens: null, + error: 'Google permissions changed. Please reconnect to continue.', + }); + + // Nudge any already-open window to re-read state. The renderer's initial + // mount also re-reads, so the prompt shows even if no window is up yet. + emitOAuthEvent({ provider: 'google', success: false }); + } catch (error) { + console.error('[OAuth] Google scope migration check failed:', error); + } +} + /** * Get access token for a provider (internal use only) * Refreshes token if expired diff --git a/apps/x/apps/renderer/package.json b/apps/x/apps/renderer/package.json index a193b3f1..67876189 100644 --- a/apps/x/apps/renderer/package.json +++ b/apps/x/apps/renderer/package.json @@ -9,6 +9,7 @@ "preview": "vite preview" }, "dependencies": { + "@eigenpal/docx-editor-react": "^1.0.3", "@radix-ui/react-avatar": "^1.1.11", "@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-context-menu": "^2.2.16", @@ -46,6 +47,15 @@ "motion": "^12.23.26", "nanoid": "^5.1.6", "posthog-js": "^1.332.0", + "prosemirror-commands": "^1.7.1", + "prosemirror-dropcursor": "^1.8.2", + "prosemirror-history": "^1.5.0", + "prosemirror-keymap": "^1.2.3", + "prosemirror-model": "^1.25.7", + "prosemirror-state": "^1.4.4", + "prosemirror-tables": "^1.8.5", + "prosemirror-transform": "^1.12.0", + "prosemirror-view": "^1.41.8", "radix-ui": "^1.4.3", "react": "^19.2.0", "react-dom": "^19.2.0", diff --git a/apps/x/apps/renderer/src/App.tsx b/apps/x/apps/renderer/src/App.tsx index 6619bbe4..fc36df68 100644 --- a/apps/x/apps/renderer/src/App.tsx +++ b/apps/x/apps/renderer/src/App.tsx @@ -5,7 +5,7 @@ import { RunEvent, ListRunsResponse } from '@x/shared/src/runs.js'; import type { LanguageModelUsage, ToolUIPart } from 'ai'; import './App.css' import z from 'zod'; -import { Bug, CheckIcon, LoaderIcon, PanelLeftIcon, ArrowRight, MessageSquare, ChevronLeftIcon, ChevronRightIcon, MoreHorizontal, Plus, HistoryIcon } from 'lucide-react'; +import { CheckIcon, LoaderIcon, PanelLeftIcon, ArrowRight, MessageSquare, ChevronLeftIcon, ChevronRightIcon, Plus, HistoryIcon } from 'lucide-react'; import { cn } from '@/lib/utils'; import { MarkdownEditor, type MarkdownEditorHandle } from './components/markdown-editor'; import { ChatSidebar } from './components/chat-sidebar'; @@ -18,6 +18,7 @@ import { BasesView, type BaseConfig, DEFAULT_BASE_CONFIG } from '@/components/ba import { ImageFileViewer } from '@/components/image-file-viewer'; import { VideoFileViewer } from '@/components/video-file-viewer'; import { AudioFileViewer } from '@/components/audio-file-viewer'; +import { DocxFileViewer } from '@/components/docx-file-viewer'; import { PersistentViewerCache } from '@/components/persistent-viewer-cache'; import { UnsupportedFileViewer } from '@/components/unsupported-file-viewer'; import { getViewerType, isCacheableViewerPath } from '@/lib/file-types'; @@ -66,12 +67,6 @@ import { } from "@/components/ui/sidebar" import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" import { Button } from "@/components/ui/button" import { Toaster } from "@/components/ui/sonner" import { BillingErrorDialog } from "@/components/billing-error-dialog" @@ -1007,7 +1002,7 @@ function App() { voice.start() }, [voice]) - const handlePromptSubmitRef = useRef<((message: PromptInputMessage, mentions?: FileMention[], stagedAttachments?: StagedAttachment[], searchEnabled?: boolean) => Promise) | null>(null) + const handlePromptSubmitRef = useRef<((message: PromptInputMessage, mentions?: FileMention[], stagedAttachments?: StagedAttachment[], searchEnabled?: boolean, codeMode?: 'claude' | 'codex') => Promise) | null>(null) const pendingVoiceInputRef = useRef(false) // Palette: per-tab editor handles for capturing cursor context on Cmd+K, and pending payload @@ -2299,6 +2294,19 @@ function App() { status: 'running', timestamp: Date.now(), }]) + // Detect acpx-driven coding-agent runs so the composer can retroactively + // flip code mode on with the right agent (when the user reached the skill + // via plain prompt rather than the explicit toggle). + if (llmEvent.toolName === 'executeCommand') { + const input = llmEvent.input as { command?: unknown } | undefined + const cmd = typeof input?.command === 'string' ? input.command : '' + const match = cmd.match(/\bacpx\b[\s\S]*?\b(claude|codex)\b/) + if (match) { + window.dispatchEvent(new CustomEvent('code-mode-detected', { + detail: { runId: event.runId, agent: match[1] as 'claude' | 'codex' }, + })) + } + } } else if (llmEvent.type === 'finish-step') { const nextUsage = normalizeUsage(llmEvent.usage) if (nextUsage) { @@ -2413,7 +2421,7 @@ function App() { return next }) - if (event.toolCallId && event.toolName !== 'executeCommand') { + if (event.toolCallId) { setToolOpenForTab(activeChatTabIdRef.current, event.toolCallId, false) } @@ -2591,6 +2599,7 @@ function App() { mentions?: FileMention[], stagedAttachments: StagedAttachment[] = [], searchEnabled?: boolean, + codeMode?: 'claude' | 'codex', ) => { if (isProcessing) return @@ -2702,6 +2711,7 @@ function App() { voiceInput: pendingVoiceInputRef.current || undefined, voiceOutput: ttsEnabledRef.current ? ttsModeRef.current : undefined, searchEnabled: searchEnabled || undefined, + codeMode: codeMode || undefined, middlePaneContext, }) analytics.chatMessageSent({ @@ -2717,6 +2727,7 @@ function App() { voiceInput: pendingVoiceInputRef.current || undefined, voiceOutput: ttsEnabledRef.current ? ttsModeRef.current : undefined, searchEnabled: searchEnabled || undefined, + codeMode: codeMode || undefined, middlePaneContext, }) analytics.chatMessageSent({ @@ -5312,25 +5323,6 @@ function App() { if (tabId === activeChatTabId) return activeChatTabState return chatViewStateByTab[tabId] ?? emptyChatTabState }, [activeChatTabId, activeChatTabState, chatViewStateByTab, emptyChatTabState]) - const activeRunIdForDownload = activeChatTabState.runId - const handleDownloadActiveChatLog = useCallback(async () => { - if (!activeRunIdForDownload) { - toast.error('No chat log available yet') - return - } - - try { - const result = await window.ipc.invoke('runs:downloadLog', { runId: activeRunIdForDownload }) - if (result.success) { - toast.success('Chat log saved') - } else if (result.error) { - toast.error(result.error) - } - } catch (err) { - console.error('Download chat log failed:', err) - toast.error('Failed to download chat log') - } - }, [activeRunIdForDownload]) const selectedTask = selectedBackgroundTask ? backgroundTasks.find(t => t.name === selectedBackgroundTask) : null @@ -5517,33 +5509,6 @@ function App() { New chat )} - - - - - - - - Chat options - - - { - void handleDownloadActiveChatLog() - }} - > - - Download chat log - - - {/* Trailing layout control. Always mounted (just toggled invisible when inactive) so its -webkit-app-region:no-drag rect is stable — a freshly-mounted no-drag button inside the drag-region header @@ -5654,7 +5619,11 @@ function App() { remove: knowledgeActions.remove, copyPath: knowledgeActions.copyPath, revealInFileManager: knowledgeActions.revealInFileManager, + createNote: knowledgeActions.createNote, + createFolder: knowledgeActions.createFolder, + onOpenInNewTab: knowledgeActions.onOpenInNewTab, }} + onNavigate={(path) => { void navigateToView({ type: 'workspace', path: path === WORKSPACE_ROOT ? undefined : path }) }} onOpenNote={(path) => navigateToFile(path)} onCreateWorkspace={async (name) => { await knowledgeActions.createWorkspace(name) }} /> @@ -5880,6 +5849,10 @@ function App() {
+ ) : selectedPath && getViewerType(selectedPath) === 'docx' ? ( +
+ +
) : (
@@ -5962,7 +5935,6 @@ function App() { const response = tabState.permissionResponses.get(item.id) || null return ( - {rendered} handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'session')} onApproveAlways={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'approve', 'always')} onDeny={() => handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny')} + onSwitchAgent={async (newAgent) => { + const runIdForSwitch = tab.runId + await handlePermissionResponse(permRequest.toolCall.toolCallId, permRequest.subflow, 'deny') + window.dispatchEvent(new CustomEvent('code-mode-detected', { + detail: { runId: runIdForSwitch, agent: newAgent }, + })) + if (runIdForSwitch) { + try { + await window.ipc.invoke('runs:createMessage', { + runId: runIdForSwitch, + message: `Use ${newAgent === 'claude' ? 'Claude Code' : 'Codex'} instead — rerun the same task with the same prompt, just swap the agent binary to \`${newAgent}\`.`, + codeMode: newAgent, + }) + } catch (err) { + console.error('Failed to send swap-agent follow-up', err) + } + } + }} isProcessing={isActive && isProcessing} response={response} /> + {rendered} ) } @@ -5984,6 +5975,7 @@ function App() { handleAskHumanResponse(request.toolCallId, request.subflow, response)} isProcessing={isActive && isProcessing} /> diff --git a/apps/x/apps/renderer/src/components/ai-elements/ask-human-request.tsx b/apps/x/apps/renderer/src/components/ai-elements/ask-human-request.tsx index 2e92e2ca..6571e54e 100644 --- a/apps/x/apps/renderer/src/components/ai-elements/ask-human-request.tsx +++ b/apps/x/apps/renderer/src/components/ai-elements/ask-human-request.tsx @@ -9,6 +9,7 @@ import { useState, useRef, useEffect } from "react"; export type AskHumanRequestProps = ComponentProps<"div"> & { query: string; + options?: string[]; onResponse: (response: string) => void; isProcessing?: boolean; }; @@ -16,17 +17,21 @@ export type AskHumanRequestProps = ComponentProps<"div"> & { export const AskHumanRequest = ({ className, query, + options, onResponse, isProcessing = false, ...props }: AskHumanRequestProps) => { const [response, setResponse] = useState(""); const textareaRef = useRef(null); + const hasOptions = Array.isArray(options) && options.length > 0; useEffect(() => { - // Auto-focus the textarea when component mounts - textareaRef.current?.focus(); - }, []); + // Auto-focus the textarea when in free-text mode; nothing to focus for buttons. + if (!hasOptions) { + textareaRef.current?.focus(); + } + }, [hasOptions]); const handleSubmit = () => { const trimmed = response.trim(); @@ -36,6 +41,11 @@ export const AskHumanRequest = ({ } }; + const handleOptionClick = (option: string) => { + if (isProcessing) return; + onResponse(option); + }; + const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); @@ -65,30 +75,47 @@ export const AskHumanRequest = ({ {query}

-
-