From fa4299c5b8def23625e843ea1c9d507277f969ed Mon Sep 17 00:00:00 2001 From: yoji export Date: Tue, 1 Dec 2026 14:40:59 +0000 Subject: [PATCH] Export yoji from 0c1f35fd9c4c --- README.md | 2 +- convex/adapters/capy.ts | 51 ++++-- convex/agents.ts | 50 ++++-- convex/agentsCapyServer.test.ts | 166 ++++++++++++++++++ convex/capy.ts | 13 +- convex/config.ts | 9 +- convex/integrationsSchema.ts | 5 + docs/agents.md | 13 ++ docs/self-hosting.md | 2 +- src/renderer/src/App.tsx | 3 +- src/renderer/src/integrationsData.test.ts | 13 ++ src/renderer/src/integrationsData.ts | 3 + src/renderer/src/layers/SettingsAgents.tsx | 63 ++++++- .../src/layers/SettingsAgentsServer.test.ts | 110 ++++++++++++ .../src/layers/SettingsIntegrations.css | 9 + src/shared/agentAdapter.ts | 3 + src/shared/captains.ts | 4 +- src/shared/capyLinks.test.ts | 14 +- src/shared/capyLinks.ts | 37 ++-- src/shared/capyServer.test.ts | 143 +++++++++++++++ src/shared/capyServer.ts | 53 ++++++ src/shared/config.ts | 17 ++ src/shared/driveFiles.ts | 26 +-- src/shared/i18n/locales/de/settings.ts | 10 ++ src/shared/i18n/locales/en/settings.ts | 10 ++ src/shared/i18n/locales/es/settings.ts | 10 ++ src/shared/i18n/locales/fr/settings.ts | 10 ++ src/shared/i18n/locales/ja/settings.ts | 10 ++ src/shared/integrations.ts | 18 +- 29 files changed, 796 insertions(+), 81 deletions(-) create mode 100644 convex/agentsCapyServer.test.ts create mode 100644 src/renderer/src/layers/SettingsAgentsServer.test.ts create mode 100644 src/shared/capyServer.test.ts create mode 100644 src/shared/capyServer.ts diff --git a/README.md b/README.md index c237581..d7e69e9 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ yoji Agent (⌘J) and AI task drafts run on the model you connect in Settings | Google Calendar | Shows your calendars, and edits events you change in yoji | A Google OAuth client | [google.md](docs/google.md) | | Slack | Mentions and DMs in the Inbox, with threads, replies, reactions and files | Your own Slack app | [slack.md](docs/slack.md) | | Asana | Tasks and comments in the Inbox, with replies | An Asana OAuth app | [asana.md](docs/asana.md) | -| Capy | Captains in Agents, cards, and In flight | A Capy API key | [agents.md](docs/agents.md) | +| Capy | Captains in Agents, cards, and In flight | A Capy API key. A non-production Capy can be set under Advanced; empty, yoji uses capy.ai | [agents.md](docs/agents.md#a-non-production-capy-server) | | MCP servers | Tools that yoji Agent can call | A streamable HTTP URL, in Settings → MCP servers | [self-hosting.md](docs/self-hosting.md#mcp-servers-for-yoji-agent) | | Model providers (Anthropic, OpenAI, OpenAI-compatible) | yoji Agent and AI task drafts | An API key, in Settings → Models | [agents.md](docs/agents.md#model-providers) | diff --git a/convex/adapters/capy.ts b/convex/adapters/capy.ts index e038f4c..a2499e8 100644 --- a/convex/adapters/capy.ts +++ b/convex/adapters/capy.ts @@ -4,6 +4,7 @@ import { ConvexError } from 'convex/values'; import type { AgentAdapter, AgentCapabilities, AgentConn, AgentEvent, AgentThreadState, AgentThreadStatus } from '../../src/shared/agentAdapter'; import type { CapyAsk } from '../../src/shared/captains'; import { CAPY_WEB } from '../../src/shared/config'; +import type { CapyServer } from '../../src/shared/capyServer'; import { UPLOAD_MAX, uploadType } from '../../src/shared/uploads'; import { capyApi } from '../config'; import { fetchText, MB } from '../net'; @@ -12,7 +13,8 @@ import { internal } from '../_generated/api'; import type { ActionCtx, QueryCtx } from '../_generated/server'; import { openToken } from '../tokens'; -export type CapyConfig = Record; +/** The Capy server the key was saved for (src/shared/capyServer.ts); absent, Capy's own (capyApi, CAPY_WEB). */ +export type CapyConfig = { server?: CapyServer }; export type CapyConn = AgentConn; @@ -23,30 +25,54 @@ export async function capyConnected(ctx: QueryCtx): Promise { return !!(await capyRowOf(ctx))?.secret; } -/** Capy's row with its sealed key, as actions read it; null before Capy was ever connected. */ -export type CapyRow = { _id: string; secret?: string } | null; +/** Capy's row with its sealed key and its Capy server if one is set, as actions read it; null before Capy was ever connected. */ +export type CapyRow = { _id: string; secret?: string; server?: CapyServer } | null; export async function capyRowData(ctx: QueryCtx): Promise { const row = await capyRowOf(ctx); - return row ? (row.secret ? { _id: row._id, secret: row.secret } : { _id: row._id }) : null; + return row ? { _id: row._id, ...(row.secret ? { secret: row.secret } : {}), ...(row.server ? { server: row.server } : {}) } : null; } -/** The Capy connection from its row, key opened: the key you saved in Settings → Agents. */ +/** + * What yoji seals for a key: the key alone for Capy's own servers, as it always has, or the Capy server's API address, + * a newline and the key when one is set. A key has no whitespace (agents:connectCapy), so the two never mix up. + */ +export const capyKeyToSeal = (key: string, server?: CapyServer): string => (server ? `${server.api}\n${key}` : key); + +export const CAPY_SERVER_MOVED = 'The Capy server changed after this key was saved. Add the key again in Settings → Agents.'; + +/** + * The Capy connection from its row, key opened: the key you saved in Settings → Agents. A key sealed with a Capy server + * goes only to that server's API: the row's plain server must name the same API, or the key isn't used at all, so a + * changed row can't send it anywhere else without the key being entered again. + */ export async function capyConnOf(row: CapyRow): Promise { - const secret = row?.secret ? await openToken(row.secret, { table: 'agentConnections', field: 'secret', id: row._id }) : undefined; - return { id: 'capy', kind: 'capy', label: 'Capy', config: {}, ...(secret ? { secret } : {}) }; + const opened = row?.secret ? await openToken(row.secret, { table: 'agentConnections', field: 'secret', id: row._id }) : undefined; + const cut = opened?.indexOf('\n') ?? -1, sealedApi = cut < 0 ? undefined : opened!.slice(0, cut), secret = cut < 0 ? opened : opened!.slice(cut + 1); + if (opened && sealedApi !== row?.server?.api) throw new ConvexError(CAPY_SERVER_MOVED); + return { id: 'capy', kind: 'capy', label: 'Capy', config: row?.server ? { server: row.server } : {}, ...(secret ? { secret } : {}) }; } /** The Capy connection for an internal action, which reads the row itself; a userAction gets it from capy.ts capyAction. */ export const capyConn = async (ctx: Pick): Promise => capyConnOf(await ctx.runQuery(internal.agents.capyRow, {})); +/** + * The Capy API a connection's calls go to: its Capy server's, set in Settings → Agents; else CAPY_API_URL on the + * deployment; else Capy's own (convex/config.ts capyApi). + */ +export const capyApiOf = (conn: Pick, 'config'>): string => conn.config.server?.api ?? capyApi(); + +/** The Capy web app a connection's Captain avatars come from: its Capy server's, else CAPY_WEB. */ +export const capyWebOf = (conn: Pick, 'config'>): string => conn.config.server?.web ?? CAPY_WEB; + /** * One Capy REST call with the connection's key, within net.ts's limits: a redirect is an error, so the key never follows - * one. Capy's refusals become errors the apps show as they are. + * one. A Capy server set in Settings is a URL a user gave, so it's checked as one too (public and https). Capy's + * refusals become errors the apps show as they are. */ export async function capyRequest(conn: AgentConn, path: string, init: RequestInit = {}): Promise { if (!conn.secret) throw new ConvexError('Capy isn’t connected yet'); - const { res, text } = await fetchText(`${capyApi()}${path}`, { ...init, headers: { Authorization: `Bearer ${conn.secret}`, 'Content-Type': 'application/json', ...(init.headers as Record | undefined) } }, { name: 'Capy', timeoutMs: 30_000, maxBytes: 16 * MB }).catch((e: unknown) => { + const { res, text } = await fetchText(`${capyApiOf(conn)}${path}`, { ...init, headers: { Authorization: `Bearer ${conn.secret}`, 'Content-Type': 'application/json', ...(init.headers as Record | undefined) } }, { name: 'Capy', timeoutMs: 30_000, maxBytes: 16 * MB, ...(conn.config.server ? { userUrl: true } : {}) }).catch((e: unknown) => { throw e instanceof ProviderError ? new ConvexError(e.message) : e; }); if (res.status === 401) throw new ConvexError('Capy turned the API key down; add a new one'); @@ -65,8 +91,9 @@ const STATUSES: AgentThreadStatus[] = ['working', 'waiting', 'idle', 'failed', ' export const captainStatus = (c: Pick): AgentThreadStatus => (c.archived ? 'archived' : STATUSES.includes(c.status as AgentThreadStatus) ? (c.status as AgentThreadStatus) : 'idle'); -export const captainAvatar = (c: Pick): { image: string } | { emoji: string } => - c.avatar?.image ? { image: c.avatar.image } : c.avatar?.kind === 'emoji' && c.avatar.value ? { emoji: c.avatar.value } : { image: `${CAPY_WEB}/avatars/${/^[\w-]+$/.test(c.avatar?.value ?? '') ? c.avatar!.value : 'capy-avatar-1'}.png` }; +/** A Captain's face: its own image or emoji, else one of Capy's stock avatars on `web`, the connection's Capy web app (capyWebOf). */ +export const captainAvatar = (c: Pick, web = CAPY_WEB): { image: string } | { emoji: string } => + c.avatar?.image ? { image: c.avatar.image } : c.avatar?.kind === 'emoji' && c.avatar.value ? { emoji: c.avatar.value } : { image: `${web}/avatars/${/^[\w-]+$/.test(c.avatar?.value ?? '') ? c.avatar!.value : 'capy-avatar-1'}.png` }; export const captainName = (c: Pick): string => c.name || c.title || 'Captain'; @@ -110,7 +137,7 @@ export const capyAdapter: AgentAdapter = { ...(c.needsYou && c.ask?.text ? { ask: c.ask.text } : {}), unread: c.hasUnreads, lastActivityAt: Date.parse(c.lastActivityAt) || 0, - avatar: captainAvatar(c), + avatar: captainAvatar(c, capyWebOf(conn)), color: c.avatar?.background ?? '#5AAB6B', })); return { threads, events: [] }; diff --git a/convex/agents.ts b/convex/agents.ts index e2fe950..326e6c4 100644 --- a/convex/agents.ts +++ b/convex/agents.ts @@ -14,7 +14,9 @@ import { CAPY_CONNECTION, issueTruths, itemIssue, mirrorCanvasChats, mirrorCanva import { sortCaptains, type Captain } from '../src/shared/captains'; import type { FlightIssue, FlightThread } from '../src/shared/inFlight'; import { convexOverlay } from './overlay'; -import { capyAdapter, capyRequest, capyRowData, capyRowOf, type CapyRow } from './adapters/capy'; +import { capyAdapter, capyApiOf, capyKeyToSeal, capyRequest, capyRowData, capyRowOf, type CapyRow } from './adapters/capy'; +import { CAPY_SERVER_PROBLEMS, capyHost, capyServerOf } from '../src/shared/capyServer'; +import { urlRefusal } from './net'; import { mcpAdapter } from './adapters/mcp'; import type { AgentConnection } from '../src/shared/agentAdapter'; import { CANVAS } from '../src/shared/canvasAgent'; @@ -116,7 +118,7 @@ export const connections = userQuery({ args: {}, handler: async (ctx): Promise => { const row = await capyRowOf(ctx), caps = capyAdapter.capabilities({}); - const capy: AgentConnection[] = row?.secret ? [{ id: row._id, kind: 'capy', label: row.label, status: row.status, capabilities: caps }] : []; + const capy: AgentConnection[] = row?.secret ? [{ id: row._id, kind: 'capy', label: row.label, status: row.status, capabilities: caps, ...(row.server ? { server: row.server } : {}) }] : []; const mcp = (await ctx.db.query('connections').withIndex('by_provider', (q) => q.eq('provider', CANVAS)).collect()).flatMap((c): AgentConnection[] => c.agent ? [{ id: c._id, kind: 'mcp', label: c.agent.label, status: c.status, capabilities: mcpAdapter.capabilities(c.agent) }] : []); return [...capy, ...mcp]; @@ -135,28 +137,48 @@ export const capyLoad = internalQuery({ handler: async (ctx): Promise> => ({ owner: await isOwner(ctx), data: await capyRowData(ctx) }), }); -/** Writes Capy's row: a sealed key, or none to disconnect. With onlyNew, a row that's already there stays as it is. */ +/** + * Writes Capy's row: a sealed key, or none to disconnect, with the Capy server it was sealed for (none for Capy's own, + * which leaves the row as it always was). With onlyNew, a row that's already there stays as it is. + */ export const saveCapy = internalMutation({ - args: { secret: v.optional(v.string()), onlyNew: v.optional(v.boolean()) }, - handler: async (ctx, { secret, onlyNew }): Promise => { + args: { secret: v.optional(v.string()), server: v.optional(v.object({ web: v.string(), api: v.string() })), onlyNew: v.optional(v.boolean()) }, + handler: async (ctx, { secret, server, onlyNew }): Promise => { const row = await capyRowOf(ctx), now = Date.now(); if (row && onlyNew) return false; - if (row) await ctx.db.patch(row._id, { secret, status: 'active', error: undefined, updatedAt: now }); - else await ctx.db.insert('agentConnections', { kind: 'capy', label: 'Capy', secret, status: 'active', createdAt: now, updatedAt: now }); + if (row) await ctx.db.patch(row._id, { secret, server, status: 'active', error: undefined, updatedAt: now }); + else await ctx.db.insert('agentConnections', { kind: 'capy', label: 'Capy', secret, ...(server ? { server } : {}), status: 'active', createdAt: now, updatedAt: now }); if (secret) await ensurePolling(ctx); return true; }, }); -/** Connects Capy with an API key from Capy's settings: checked against Capy first, then stored sealed. */ +/** + * Connects Capy with an API key from Capy's settings: checked against Capy first, then stored sealed. `server` is the + * optional Capy server from Settings → Agents → Capy → Advanced (src/shared/capyServer.ts); left out, or empty, the key + * goes to Capy's own as it always has. Set, the key is checked on that server and sealed together with its API address + * (adapters/capy.ts capyKeyToSeal), so it's only ever sent there. A refusal names the server that refused, because a key + * made on one Capy is turned down by any other. + */ export const connectCapy = userAction({ - args: { apiKey: v.string() }, - handler: async (ctx, { apiKey }): Promise => { + args: { apiKey: v.string(), server: v.optional(v.object({ web: v.string(), api: v.string() })) }, + handler: async (ctx, { apiKey, server: typed }): Promise => { const key = apiKey.trim(); if (!/^\S{8,512}$/.test(key)) throw new ConvexError('That doesn’t look like a Capy API key'); - const secret = await sealInput(key, { table: 'agentConnections', field: 'secret', id: '' }); - await capyRequest({ id: 'capy', kind: 'capy', label: 'Capy', config: {}, secret: key }, '/captains'); - await ctx.runMutation(internal.agents.saveCapy, { secret }); + const checked = typed ? capyServerOf(typed.web, typed.api) : { server: null }; + if ('problem' in checked) throw new ConvexError(CAPY_SERVER_PROBLEMS[checked.problem]); + const server = checked.server ?? undefined; + for (const url of server ? [server.web, server.api] : []) { + const why = urlRefusal(url); + if (why) throw new ConvexError(why); + } + const at = { table: 'agentConnections', field: 'secret', id: '' } as const; + const sealed = await sealInput(key, at), secret = server ? await sealInput(capyKeyToSeal(key, server), at) : sealed; + const conn = { id: 'capy', kind: 'capy' as const, label: 'Capy', config: server ? { server } : {}, secret: key }; + await capyRequest(conn, '/captains').catch((e: unknown) => { + throw e instanceof ConvexError && String(e.data).startsWith('Capy turned the API key down') ? new ConvexError(`Capy turned the API key down at ${capyHost(capyApiOf(conn))}. A key works only on the Capy server it was made on.`) : e; + }); + await ctx.runMutation(internal.agents.saveCapy, { secret, ...(server ? { server } : {}) }); const row = await ctx.runQuery(internal.agents.capyRow, {}); if (row) await bindRow(ctx, 'agentConnections', row._id); return null; @@ -168,7 +190,7 @@ export const disconnectCapy = userMutation({ args: {}, handler: async (ctx): Promise => { const row = await capyRowOf(ctx); - if (row) await ctx.db.patch(row._id, { secret: undefined, updatedAt: Date.now() }); + if (row) await ctx.db.patch(row._id, { secret: undefined, server: undefined, updatedAt: Date.now() }); return null; }, }); diff --git a/convex/agentsCapyServer.test.ts b/convex/agentsCapyServer.test.ts new file mode 100644 index 0000000..49b500c --- /dev/null +++ b/convex/agentsCapyServer.test.ts @@ -0,0 +1,166 @@ +/// +import { convexTest } from 'convex-test'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { api, internal } from './_generated/api'; +import schema from './schema'; +import { CAPY_SERVER_MOVED } from './adapters/capy'; +import { sealedBefore } from './sealed.fixture'; + +// The opt-in Capy server (Settings → Agents → Capy → Advanced) on the backend. Left out, every request and stored value +// is what yoji sent and stored before it existed. Set, every Capy call goes to its API, its stock avatars come from its +// web address, and the key is sealed with its API address, so the key never goes anywhere else. example.com stands in +// for any other Capy. + +const modules = import.meta.glob('./**/*.ts'); +const SERVER = { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' }; + +/** A fake Capy that knows one key, recording every URL and key it was sent, and lists one Captain with a stock avatar. */ +function capy(good = 'capy-saved') { + const calls: { url: string; auth: string | null }[] = []; + vi.stubGlobal('fetch', vi.fn(async (input: string | URL | Request, init: RequestInit = {}) => { + const auth = new Headers(init.headers).get('Authorization'); + calls.push({ url: String(input), auth }); + if (auth !== `Bearer ${good}`) return new Response('{}', { status: 401 }); + if (String(input).endsWith('/captains')) return Response.json({ items: [{ id: 'cap1', name: 'Halcyon', authorId: 'u', status: 'idle', archived: false, member: true, needsYou: false, crewNeedsYou: 0, crewCount: 0, hasUnreads: false, lastActivityAt: '2026-11-04T10:00:00Z', avatar: { kind: 'avatar', value: 'capy-avatar-3' } }] }); + return Response.json({ items: [] }); + })); + return calls; +} + +beforeEach(() => { + vi.stubEnv('YOJI_DEV_OPEN', '1'); + vi.stubEnv('YOJI_ENCRYPTION_KEY', btoa(String.fromCharCode(...new Uint8Array(32).fill(5)))); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +const row = (t: ReturnType) => t.run((ctx) => ctx.db.query('agentConnections').first()); +const urls = (calls: { url: string }[]) => [...new Set(calls.map((c) => c.url.replace(/\/captains.*$/, '/captains')))]; + +describe('Capy with no Capy server set', () => { + it('sends and stores exactly what it did before the setting existed', async () => { + vi.stubEnv('CAPY_API_URL', ''); + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved' }); + expect(calls).toEqual([{ url: 'https://api.capy.ai/api/v1/captains', auth: 'Bearer capy-saved' }]); + const saved = (await row(t))!; + expect(Object.keys(saved).sort()).toEqual(['_creationTime', '_id', 'createdAt', 'kind', 'label', 'secret', 'status', 'updatedAt']); + expect(saved).toMatchObject({ kind: 'capy', label: 'Capy', status: 'active' }); + expect(saved.secret).toMatch(/^yoji-enc:v3:/); + const [listed] = await t.query(api.agents.connections, {}); + expect(listed).not.toHaveProperty('server'); + calls.length = 0; + const [c] = await t.action(api.capy.list, {}); + expect(urls(calls)).toEqual(['https://api.capy.ai/api/v1/captains']); + expect(c!.avatar).toEqual({ image: 'https://capy.ai/avatars/capy-avatar-3.png' }); + }); + + it('keeps using CAPY_API_URL, and an empty server sent by an app counts as none', async () => { + vi.stubEnv('CAPY_API_URL', 'https://capy-api.example.net/api/v1/'); + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: { web: ' ', api: '' } }); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: { web: 'https://capy.ai', api: 'https://api.capy.ai/api/v1/' } }); + await t.action(api.capy.list, {}); + expect(urls(calls)).toEqual(['https://capy-api.example.net/api/v1/captains']); + expect(await row(t)).not.toHaveProperty('server'); + }); + + it('still opens a key stored before v3 (#750)', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.mutation(internal.agents.saveCapy, { secret: await sealedBefore('capy-saved') }); + await t.action(api.capy.list, {}); + expect(calls.map((c) => c.auth)).toEqual(['Bearer capy-saved']); + }); +}); + +describe('Capy with a Capy server set', () => { + beforeEach(() => vi.stubEnv('CAPY_API_URL', 'https://capy-api.example.net/api/v1')); + + it('checks the key there, stores the server, and sends every call there, ahead of CAPY_API_URL', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: { web: 'https://capy.example.com/', api: 'https://api.capy.example.com/api/v1/' } }); + const saved = (await row(t))!; + expect(saved.server).toEqual(SERVER); + expect(saved.secret).toMatch(/^yoji-enc:v3:/); + expect(saved.secret).not.toContain('capy-saved'); + expect(await t.query(api.agents.connections, {})).toMatchObject([{ kind: 'capy', server: SERVER }]); + const [c] = await t.action(api.capy.list, {}); + expect(c!.avatar).toEqual({ image: 'https://capy.example.com/avatars/capy-avatar-3.png' }); + expect(urls(calls)).toEqual(['https://api.capy.example.com/api/v1/captains']); + expect(calls.every((x) => x.auth === 'Bearer capy-saved')).toBe(true); + }); + + it('names the server that turned a key down', async () => { + const t = convexTest(schema, modules); + capy(); + await expect(t.action(api.agents.connectCapy, { apiKey: 'capy-prod-key', server: SERVER })).rejects.toThrow('Capy turned the API key down at api.capy.example.com. A key works only on the Capy server it was made on.'); + await expect(t.action(api.agents.connectCapy, { apiKey: 'capy-prod-key' })).rejects.toThrow('Capy turned the API key down at capy-api.example.net.'); + expect(await row(t)).toBeNull(); + }); + + it('refuses a server that isn’t two public https addresses, before sending the key anywhere', async () => { + const t = convexTest(schema, modules), calls = capy(); + for (const [server, why] of [ + [{ web: 'http://capy.example.com', api: SERVER.api }, 'full https://'], + [{ web: SERVER.web, api: 'http://api.capy.example.com/api/v1' }, 'full https://'], + [{ web: SERVER.web, api: '' }, 'or neither'], + [{ web: 'https://capy.example.com/drive', api: SERVER.api }, 'no path'], + [{ web: SERVER.web, api: 'https://10.0.0.8/api/v1' }, 'private or local address'], + [{ web: 'https://localhost', api: SERVER.api }, 'private or local address'], + ] as const) + await expect(t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server }), JSON.stringify(server)).rejects.toThrow(why); + expect(calls).toEqual([]); + expect(await row(t)).toBeNull(); + }); + + it('never sends a key to a server other than the one it was saved for, until the key is entered again', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: SERVER }); + const saved = (await row(t))!; + calls.length = 0; + await t.run((ctx) => ctx.db.patch(saved._id, { server: { web: SERVER.web, api: 'https://elsewhere.example.org/api/v1' } })); + await expect(t.action(api.capy.list, {})).rejects.toThrow(CAPY_SERVER_MOVED); + await t.run((ctx) => ctx.db.patch(saved._id, { server: undefined })); + await expect(t.action(api.capy.list, {})).rejects.toThrow(CAPY_SERVER_MOVED); + expect(calls).toEqual([]); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: { web: SERVER.web, api: 'https://elsewhere.example.org/api/v1' } }); + await t.action(api.capy.list, {}); + expect(urls(calls)).toEqual(['https://elsewhere.example.org/api/v1/captains']); + }); + + it('never sends a key saved for Capy’s own servers to a server added to its row later', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved' }); + const saved = (await row(t))!; + calls.length = 0; + await t.run((ctx) => ctx.db.patch(saved._id, { server: SERVER })); + await expect(t.action(api.capy.list, {})).rejects.toThrow(CAPY_SERVER_MOVED); + expect(calls).toEqual([]); + }); + + it('keeps the binding through tokens:reseal, and forgets the server on Disconnect', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: SERVER }); + await t.action(internal.tokens.reseal, {}); + calls.length = 0; + await t.action(api.capy.list, {}); + expect(urls(calls)).toEqual(['https://api.capy.example.com/api/v1/captains']); + await t.mutation(api.agents.disconnectCapy, {}); + const left = (await row(t))!; + expect(left).not.toHaveProperty('server'); + expect(left).not.toHaveProperty('secret'); + }); + + it('goes back to Capy’s own servers when the key is saved with the server cleared', async () => { + const t = convexTest(schema, modules), calls = capy(); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved', server: SERVER }); + await t.action(api.agents.connectCapy, { apiKey: 'capy-saved' }); + expect(await row(t)).not.toHaveProperty('server'); + calls.length = 0; + await t.action(api.capy.list, {}); + expect(urls(calls)).toEqual(['https://capy-api.example.net/api/v1/captains']); + }); +}); diff --git a/convex/capy.ts b/convex/capy.ts index 8453ff5..414ddc1 100644 --- a/convex/capy.ts +++ b/convex/capy.ts @@ -16,7 +16,7 @@ import { checkPulls } from './pulls'; import { appTier } from './presence'; import { generate } from './ai'; import { LANGUAGE_ENGLISH } from '../src/shared/i18n'; -import { capyAdapter, capyConn, capyConnOf, capyConnected, type CapyRow, capyRequest, type CapyConn, captainAvatar, captainName, captainStatus, transcript as readTranscript, type RawCaptain as Raw, type TranscriptItem as Item, type TranscriptPage as Page } from './adapters/capy'; +import { capyAdapter, capyConn, capyConnOf, capyConnected, capyWebOf, type CapyRow, capyRequest, type CapyConn, captainAvatar, captainName, captainStatus, transcript as readTranscript, type RawCaptain as Raw, type TranscriptItem as Item, type TranscriptPage as Page } from './adapters/capy'; import { CAPY_CONNECTION, captainThread, crewThread, issueItem, issueTruths, syncCapyThreads, syncCapyWorkItems } from './agentTables'; import { briefLine, CREW_IDLE, crewListed, listedState, TASKS_UNREAD, threadShown, waitCall, waitReason, type CrewIssue, type FlightHide, type FlightIssue, type FlightThread, type IssueMeta, type IssueState } from '../src/shared/inFlight'; @@ -37,11 +37,12 @@ export function capyAction(def: { args: A; hand return userAction({ args: def.args, load: capyLoad(), handler: async (ctx, args, row) => def.handler(ctx, args, await capyConnOf(row)) }); } -const captain = (c: Raw): Captain => ({ +/** A Captain as the apps show it; `web` is the connection's Capy web app (capyWebOf), where stock avatars live. */ +const captain = (c: Raw, web: string): Captain => ({ id: c.id, name: captainName(c), color: c.avatar?.background ?? '#5AAB6B', - avatar: captainAvatar(c), + avatar: captainAvatar(c, web), status: captainStatus(c), needsYou: c.needsYou, crewNeedsYou: c.crewNeedsYou ?? 0, @@ -113,7 +114,7 @@ async function withAsks(ctx: ActionCtx, conn: CapyConn, items: Raw[], crews: Map const r = word(id); if (r && !askAnswered(r) && !r.acked) asks.set(id, { ...r, acked: true }); } - const list = items.map(captain).map((c) => { + const list = items.map((c) => captain(c, capyWebOf(conn))).map((c) => { const crew = crews.get(c.id); return crew ? { ...c, crewNeedsYou: crew.filter((t) => crewWaitsOnYou(t) && !askOff(word(t.id))).length } : c; }); @@ -916,7 +917,7 @@ async function senderFaces(ctx: ActionCtx, conn: CapyConn, ids: string[]): Promi ids.filter((t) => !mine.has(t) && !stored.get(t)?.faced).map(async (t): Promise => { const cap = await capy(conn, `/captains/${t}`).catch(() => null); if (cap) { - const c = captain(cap); + const c = captain(cap, capyWebOf(conn)); return { threadId: t, title: c.name, color: c.color, avatar: c.avatar, faced: true }; } const title = stored.get(t)?.title ?? (await capy<{ title?: string | null }>(conn, `/threads/${t}`).then((r) => r.title || 'Another agent', () => null)); @@ -1146,7 +1147,7 @@ export const view = capyAction({ console.info(`yoji: ${raw.name || id} (${id}) needs you, and its newest message ${asked.id} carries no card, so the reply box shows under it; ${open} open ${open === 1 ? 'card' : 'cards'} above.`); } return { - captain: { ...captain(raw), crewNeedsYou: crew.filter((t) => !asks.get(t.id)?.acked).length, ...answered }, + captain: { ...captain(raw, capyWebOf(conn)), crewNeedsYou: crew.filter((t) => !asks.get(t.id)?.acked).length, ...answered }, needs: needsYouLines(digest.markdown ?? ''), crew: crew.map((t): CaptainView['crew'][number] => { const form = liveForm(t); diff --git a/convex/config.ts b/convex/config.ts index 7d74fc9..48ec52a 100644 --- a/convex/config.ts +++ b/convex/config.ts @@ -1,5 +1,7 @@ // The deployment's external origins, read from its Convex env (npx convex env set). Each is read when it is used, so // a missing one fails only the feature that needs it, with an error that names the variable. +import { CAPY_API } from '../src/shared/config'; + declare const process: { env: Record }; function env(name: string, fallback?: string): string { @@ -11,5 +13,8 @@ function env(name: string, fallback?: string): string { /** This deployment's HTTP actions origin (https://.convex.site), which Convex sets on every deployment. */ export const siteUrl = (): string => env('CONVEX_SITE_URL'); -/** Capy's REST API. CAPY_API_URL overrides the public one. */ -export const capyApi = (): string => env('CAPY_API_URL', 'https://api.capy.ai/api/v1'); +/** + * Capy's REST API for a connection with no Capy server set: CAPY_API_URL, else Capy's own (CAPY_API). A Capy server set in + * Settings → Agents comes first (adapters/capy.ts capyApiOf). + */ +export const capyApi = (): string => env('CAPY_API_URL', CAPY_API); diff --git a/convex/integrationsSchema.ts b/convex/integrationsSchema.ts index c2b47ea..6e101ce 100644 --- a/convex/integrationsSchema.ts +++ b/convex/integrationsSchema.ts @@ -307,6 +307,11 @@ export const agentConnectionFields = { local: v.optional(v.object({ agent: v.union(v.literal('claude'), v.literal('codex')), cwd: v.optional(v.string()) })), remote: v.optional(v.object({ url: v.string() })), cursor: v.optional(v.object({ repo: v.optional(v.string()), ref: v.optional(v.string()) })), + /** + * Capy only, and only when set in Settings → Agents → Capy → Advanced: a Capy server other than Capy's own + * (src/shared/capyServer.ts). Absent on every connection made without it, which talks to Capy's own as it always has. + */ + server: v.optional(v.object({ web: v.string(), api: v.string() })), status: v.union(v.literal('active'), v.literal('error')), error: v.optional(v.string()), createdAt: v.number(), diff --git a/docs/agents.md b/docs/agents.md index 5b248de..44c8dd2 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -18,6 +18,19 @@ To connect Capy: `CAPY_API_URL` points yoji at a Capy API other than `https://api.capy.ai/api/v1`. Most people never set it. +#### A non-production Capy server + +Most people skip this. Settings → Agents → Capy → **Advanced** has a **Capy server** for a Capy environment other than production, such as a staging Capy. It's closed and empty by default, and while it's empty yoji talks to Capy exactly as it always has. + +- It takes two `https://` addresses, both or neither: the **web address** (for example `https://capy.example.com`), where Capy pages, links and stock Captain avatars come from, and the **API address** (for example `https://api.capy.example.com/api/v1`). Capy documents only production's pair, and its API moved off the web address once already, so yoji doesn't guess one from the other. +- The server is saved with the key. Changing it needs the key again, and a key made on one Capy is turned down by any other, so the error names the server that refused it. +- yoji seals the server's API address inside the encrypted key (`convex/adapters/capy.ts`). If the stored server ever stops matching it, yoji refuses to use the key instead of sending it anywhere else, until you enter it again. +- Links to threads, issues, Drive and Capy's settings open on the web address in both apps. Links on `capy.ai` still open from chat text too. +- The phone app has no Capy key settings. It follows the server saved from the Mac. +- Sending a file to a Captain from the Mac works only if that Capy hands out upload links on Capy's own file bucket, because the Mac sends files only to upload hosts it knows (`src/main/guard.ts`). The phone app has no such list. + +Which API yoji calls: the Capy server's API address when one is set; otherwise `CAPY_API_URL`; otherwise `https://api.capy.ai/api/v1`. + Capy has no push, so yoji polls it. The poll runs only while a yoji app is open, and stops while nothing is listening. A message you send from yoji is a normal message in the Captain's Capy thread. ### Model providers diff --git a/docs/self-hosting.md b/docs/self-hosting.md index 137f562..e47643a 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -89,7 +89,7 @@ yoji reads these from the Convex deployment's environment (`npx convex env set`, | `ASANA_CLIENT_ID`, `ASANA_CLIENT_SECRET` | Asana tasks and comments in the Inbox. | [asana.md](asana.md) | | `GEMINI_API_KEY` | Voice input through Gemini Flash while no ElevenLabs key is added in Settings → Integrations. A key from Google AI Studio. | [agents.md](agents.md#voice-input) | | `FIRECRAWL_API_KEY` | Web search in plain Chats while no Firecrawl key is added in Settings › Chats. A key from firecrawl.dev. | [agents.md](agents.md#web-search-in-chats) | -| `CAPY_API_URL` | A Capy API other than `https://api.capy.ai/api/v1`. | [agents.md](agents.md) | +| `CAPY_API_URL` | A Capy API other than `https://api.capy.ai/api/v1`. A Capy server set in Settings → Agents → Capy → Advanced takes precedence over it. | [agents.md](agents.md#a-non-production-capy-server) | | `GITHUB_TOKEN` | Lets ship cards in Captain chats see when their pull request lands in a private repository. A read-only token is enough: a fine-grained token with Contents and Pull requests set to Read on those repositories. Public repositories work without it. | [cards.md](cards.md) | | `YOJI_ENCRYPTION_KEY_PREVIOUS` | Only while rotating: the old encryption key, so tokens sealed under it still open until they are resealed. | [Rotate YOJI_ENCRYPTION_KEY](#rotate-yoji_encryption_key) | | `YOJI_ALLOW_PRIVATE_URLS` | `1` lets MCP servers and OpenAI-compatible model servers use private and local addresses (`10.x`, `192.168.x`, `*.local`, `localhost` and the like), and `http://` on the backend's own machine. `pnpm run setup` sets it on a local deployment (`convex dev --local`); every other backend needs it set by hand. Set it only on a backend whose network you trust: it lets anyone signed in to yoji make the backend call those addresses. Without it, yoji checks the address as written, not where its name resolves (see [Reachability](#mcp-servers-for-yoji-agent)). | [MCP servers](#mcp-servers-for-yoji-agent) | diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 98c2b50..fd19089 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -42,7 +42,7 @@ import { AgentPanel, AgentPill } from './AgentPanel'; import { InFlight, useFlightRoom } from './InFlight'; import { listWidth } from './ListRail'; import { AgentColumn, agentWidth } from './AgentColumn'; -import { useAgentConnections, useDraftSync, useForeground, useIntegrations, useResumeSends, useSharedPrefs } from './integrationsData'; +import { useAgentConnections, useCapyWeb, useDraftSync, useForeground, useIntegrations, useResumeSends, useSharedPrefs } from './integrationsData'; import { selfAvatars } from '../../shared/integrations'; import { offersWorkItems } from '../../shared/agentAdapter'; import { ConnectionLine } from './Connection'; @@ -73,6 +73,7 @@ export function App(): ReactElement { }, [faces]); useEffect(() => trackAgentTabs(), []); useEffect(() => trackAgentChips(), []); + useCapyWeb(); const flightOffered = offersWorkItems(useAgentConnections()), flight = ui.flight && ui.flightOffered; useEffect(() => { if (flightOffered !== getUI().flightOffered) setUI({ flightOffered }); diff --git a/src/renderer/src/integrationsData.test.ts b/src/renderer/src/integrationsData.test.ts index cfa174b..87a4a4e 100644 --- a/src/renderer/src/integrationsData.test.ts +++ b/src/renderer/src/integrationsData.test.ts @@ -267,3 +267,16 @@ describe('titleRepeatsBody', () => { expect(titleRepeatsBody({ title: 'Mention', body: '' })).toBe(false); }); }); + +describe('connectCapy', () => { + it('sends just the key with no Capy server, as before the setting existed, and the server with one', async () => { + const source = connectIntegrations('https://example.convex.cloud'); + calls.length = 0; + await source.connectCapy('capy-saved'); + await source.connectCapy('capy-staging', { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' }); + expect(calls).toEqual([ + { kind: 'action', name: 'agents:connectCapy', args: { apiKey: 'capy-saved' } }, + { kind: 'action', name: 'agents:connectCapy', args: { apiKey: 'capy-staging', server: { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' } } }, + ]); + }); +}); diff --git a/src/renderer/src/integrationsData.ts b/src/renderer/src/integrationsData.ts index f02b6e9..93cd37c 100644 --- a/src/renderer/src/integrationsData.ts +++ b/src/renderer/src/integrationsData.ts @@ -20,6 +20,7 @@ import { useCapyModelsFrom, useModelDefaultsFrom, useAgentConnectionsFrom, + useCapyWebFrom, useCaptainsFrom, useFlightFrom, useInboxFrom, @@ -78,6 +79,8 @@ export const useInboxUnread = (): number => useInboxUnreadFrom(useIntegrationsSo export const useCaptains = (onScreen: boolean) => useCaptainsFrom(useIntegrationsSource(), onScreen, 'agents'); /** The agents you've connected, with what each can do; null until the backend answers. */ export const useAgentConnections = () => useAgentConnectionsFrom(useIntegrationsSource()); +/** Points Capy links at the Capy server the connection was saved with (useCapyWebFrom); App calls it once. */ +export const useCapyWeb = () => useCapyWebFrom(useIntegrationsSource()); /** What your Captains' crews have in flight, reread every 20 seconds while `open` and the app is visible. */ export const useFlight = (open: boolean) => useFlightFrom(useIntegrationsSource(), open, 'agents'); export const useCaptain = (id: string, onScreen?: boolean, landing?: PendingCaptainSend | null) => useCaptainFrom(useIntegrationsSource(), id, onScreen, landing); diff --git a/src/renderer/src/layers/SettingsAgents.tsx b/src/renderer/src/layers/SettingsAgents.tsx index 584d712..5ca0c91 100644 --- a/src/renderer/src/layers/SettingsAgents.tsx +++ b/src/renderer/src/layers/SettingsAgents.tsx @@ -10,7 +10,8 @@ import { toast, useUI } from '../store'; import { ConfirmDisconnect, PROVIDERS, ProviderCard } from './SettingsIntegrations'; import './SettingsIntegrations.css'; import { CANVAS, CANVAS_NAME } from '../../../shared/canvasAgent'; -import { CAPY_API_SETTINGS } from '../../../shared/capyLinks'; +import { capyApiSettings } from '../../../shared/capyLinks'; +import { capyServerOf, type CapyServerProblem } from '../../../shared/capyServer'; import type { Key } from '../../../shared/i18n'; import { useT } from '../../../shared/i18n/react'; @@ -143,22 +144,52 @@ function CapyDisconnect({ source }: { source: IntegrationsSource }): ReactElemen ); } -/** The key field: to connect Capy, or to replace a key you saved. */ +const SERVER_PROBLEMS: Record = { both: 'settings.agents.capyServerBoth', https: 'settings.agents.capyServerHttps', web: 'settings.agents.capyServerWebPath' }; + +/** + * The key field: to connect Capy, or to replace a key you saved. Under Advanced, closed and empty unless a Capy server + * is in use, are the two addresses of a non-production Capy (src/shared/capyServer.ts). They go with the key, so a new + * server always takes a key again; left empty, the key goes to Capy's own exactly as before. + */ function CapyKey({ capy, source }: { capy: AgentConnection | undefined; source: IntegrationsSource | null }): ReactElement { const [key, setKey] = useState(''); const [busy, setBusy] = useState(false); + const saved = capy?.server; + const [advanced, setAdvanced] = useState(!!saved); + const [web, setWeb] = useState(saved?.web ?? ''); + const [api, setApi] = useState(saved?.api ?? ''); + const [problem, setProblem] = useState(null); const t = useT(); + useEffect(() => { + setWeb(saved?.web ?? ''); + setApi(saved?.api ?? ''); + if (saved) setAdvanced(true); + }, [saved?.web, saved?.api]); const save = () => { if (!source || !key.trim() || busy) return; + const checked = capyServerOf(web, api); + if ('problem' in checked) { + setAdvanced(true); + return setProblem(t(SERVER_PROBLEMS[checked.problem])); + } + setProblem(null); setBusy(true); - source.connectCapy(key).then( + source.connectCapy(key, checked.server ?? undefined).then( () => { setKey(''); toast(capy ? t('settings.agents.savedKey') : t('settings.connectedName', { name: 'Capy' }), false, 'success'); }, - (e: unknown) => toast(integrationError(e), false, 'error'), + (e: unknown) => { + if (!checked.server) return toast(integrationError(e), false, 'error'); + setAdvanced(true); + setProblem(integrationError(e)); + }, ).finally(() => setBusy(false)); }; + const typed = (set: (v: string) => void) => (v: string) => { + set(v); + setProblem(null); + }; return ( <> {capy ? null : ( @@ -178,6 +209,28 @@ function CapyKey({ capy, source }: { capy: AgentConnection | undefined; source: +
+ +
+ {advanced ? ( +
e.key === 'Enter' && save()}> +
+ {t('settings.agents.capyServer')} + {t('settings.agents.capyServerDesc')} +
+ + + {problem ?

{problem}

:

{t('settings.agents.capyServerKey')}

} +
+ ) : null} ); } @@ -188,7 +241,7 @@ export function CapyKeyHelp(): ReactElement { return (
{t('settings.agents.capyKeyOnce')} -
diff --git a/src/renderer/src/layers/SettingsAgentsServer.test.ts b/src/renderer/src/layers/SettingsAgentsServer.test.ts new file mode 100644 index 0000000..d82749a --- /dev/null +++ b/src/renderer/src/layers/SettingsAgentsServer.test.ts @@ -0,0 +1,110 @@ +// @vitest-environment jsdom +// Settings › Agents › Capy: the Capy server under Advanced is closed and empty, and a key saved with it closed reaches +// the backend as it always did (just the key). Opened and filled, the key goes with the server; a half-filled or +// non-https server is caught before anything is sent, and a refusal from that server shows beside it. +import { act, createElement } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import type { AgentConnection } from '../../../shared/agentAdapter'; +import type { CapyServer } from '../../../shared/capyServer'; + +const state = vi.hoisted(() => ({ connections: [] as AgentConnection[], connect: vi.fn(async (_key: string, _server?: CapyServer) => null as unknown) })); +vi.mock('../integrationsData', async (original) => ({ + ...(await original()), + useAgentConnections: () => state.connections, + useIntegrationsSource: () => ({ connectCapy: state.connect, disconnectCapy: async () => null }), + useIntegrations: () => ({ connections: [], providers: [], calendars: [] }), + useModelDefaults: () => null, +})); + +beforeAll(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +}); + +const { SettingsAgents } = await import('./SettingsAgents'); +const CAPY = { id: 'c1', kind: 'capy', label: 'Capy', status: 'active', capabilities: { start: false, attachments: true, media: true, questions: true, needsYou: true, crew: true, workItems: true, cancel: false } } satisfies AgentConnection; + +let root: Root | null = null; +afterEach(() => { + act(() => root?.unmount()); + root = null; + document.body.innerHTML = ''; + state.connect.mockReset(); + state.connections = []; +}); + +function mount(): HTMLElement { + const host = document.body.appendChild(document.createElement('div')); + root = createRoot(host); + act(() => root!.render(createElement(SettingsAgents))); + return host; +} + +const input = (host: HTMLElement, sel: string) => host.querySelector(sel)!; +function type(el: HTMLInputElement, value: string) { + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(el, value); + el.dispatchEvent(new Event('input', { bubbles: true })); + }); +} +const button = (host: HTMLElement, text: string) => [...host.querySelectorAll('button')].find((b) => b.textContent === text)!; +const click = async (el: HTMLElement) => act(async () => void el.click()); + +describe('the Capy server in Settings › Agents', () => { + it('is closed and empty, and a key saved without it goes alone', async () => { + const host = mount(); + expect(host.querySelector('.si-server')).toBeNull(); + expect(button(host, 'Advanced').getAttribute('aria-expanded')).toBe('false'); + type(input(host, '.si-key input'), 'capy-saved'); + await click(button(host, 'Connect')); + expect(state.connect.mock.calls).toEqual([['capy-saved', undefined]]); + }); + + it('opened and filled, sends the key with the server', async () => { + const host = mount(); + await click(button(host, 'Advanced')); + const [web, api] = [...host.querySelectorAll('.si-server input')]; + expect(host.textContent).toContain('Only for a non-production Capy environment'); + type(web!, 'https://capy.example.com/'); + type(api!, 'https://api.capy.example.com/api/v1'); + type(input(host, '.si-key input'), 'capy-staging'); + await click(button(host, 'Connect')); + expect(state.connect.mock.calls).toEqual([['capy-staging', { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' }]]); + }); + + it('catches a half-filled or plain-http server before sending anything', async () => { + const host = mount(); + await click(button(host, 'Advanced')); + const [web, api] = [...host.querySelectorAll('.si-server input')]; + type(input(host, '.si-key input'), 'capy-staging'); + type(web!, 'https://capy.example.com'); + await click(button(host, 'Connect')); + expect(host.querySelector('.si-server .st-err')?.textContent).toBe('Give both the web address and the API address, or neither.'); + type(api!, 'http://api.capy.example.com/api/v1'); + await click(button(host, 'Connect')); + expect(host.querySelector('.si-server .st-err')?.textContent).toBe('Use full https:// addresses.'); + expect(state.connect).not.toHaveBeenCalled(); + }); + + it('shows the server’s refusal beside the server', async () => { + state.connect.mockRejectedValueOnce(new Error('Capy turned the API key down at api.capy.example.com. A key works only on the Capy server it was made on.')); + const host = mount(); + await click(button(host, 'Advanced')); + const [web, api] = [...host.querySelectorAll('.si-server input')]; + type(web!, 'https://capy.example.com'); + type(api!, 'https://api.capy.example.com/api/v1'); + type(input(host, '.si-key input'), 'capy-prod-key'); + await click(button(host, 'Connect')); + expect(host.querySelector('.si-server .st-err')?.textContent).toBe('Capy turned the API key down at api.capy.example.com. A key works only on the Capy server it was made on.'); + }); + + it('shows a saved server on the closed Advanced button, and opens with it filled in', async () => { + state.connections = [{ ...CAPY, server: { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' } }]; + const host = mount(); + const [web, api] = [...host.querySelectorAll('.si-server input')]; + expect(web!.value).toBe('https://capy.example.com'); + expect(api!.value).toBe('https://api.capy.example.com/api/v1'); + await click(host.querySelector('.si-adv button')!); + expect(host.querySelector('.si-adv button')!.textContent).toBe('Advanced: Capy server https://capy.example.com'); + }); +}); diff --git a/src/renderer/src/layers/SettingsIntegrations.css b/src/renderer/src/layers/SettingsIntegrations.css index 236a53b..89d7248 100644 --- a/src/renderer/src/layers/SettingsIntegrations.css +++ b/src/renderer/src/layers/SettingsIntegrations.css @@ -54,3 +54,12 @@ .si-key .st-in{width:220px} .si-key .si-acts{gap:6px} .si-key{padding-left:60px} +/* Settings › Agents › Capy: Advanced, and under it the Capy server of a non-production Capy (CapyKey). */ +.si-adv{padding:0 16px 10px;margin-top:-4px} +.si-adv .btn{height:26px;padding:0 8px;margin-left:-8px;font-size:12px} +.si-server{display:flex;flex-direction:column;gap:10px;padding:12px 16px 14px;border-top:1px solid var(--b1)} +.si-server label{display:flex;align-items:center;gap:12px;font-size:12.5px;color:var(--text-2)} +.si-server label span{width:96px;flex:none} +.si-server .st-in{flex:1;width:auto} +.si-server .st-err{padding:0;margin:0} +.si-server-note{margin:0;font-size:12px;line-height:1.5;color:var(--text-3)} diff --git a/src/shared/agentAdapter.ts b/src/shared/agentAdapter.ts index 498f43b..0fceb12 100644 --- a/src/shared/agentAdapter.ts +++ b/src/shared/agentAdapter.ts @@ -3,6 +3,7 @@ // capabilities what the chat may offer, so no screen knows which backend it talks to. import type { ModelChoice } from './capyModels'; +import type { CapyServer } from './capyServer'; export type AgentKind = 'capy' | 'mcp'; @@ -34,6 +35,8 @@ export interface AgentConnection { capabilities: AgentCapabilities; /** Why the connection isn't working, in words the apps show. */ error?: string; + /** Capy only: the Capy server set in Settings → Agents → Capy → Advanced; absent for Capy's own (src/shared/capyServer.ts). */ + server?: CapyServer; } /** Whether any connected agent tracks work items, which is all In flight shows; true until the list arrives, so it doesn't flicker away. */ diff --git a/src/shared/captains.ts b/src/shared/captains.ts index 8c83a62..d206f3a 100644 --- a/src/shared/captains.ts +++ b/src/shared/captains.ts @@ -1,7 +1,7 @@ // Capy Captains in Agents: your Captains (long-lived Capy agents that run a crew of threads), what each // needs from you, its recent conversation, and replying to it. The server holds the Capy API key // (convex/capy.ts); these are the shapes both apps read and the pure helpers behind them. -import { CAPY_WEB } from './config'; +import { capyWeb } from './config'; import { shipAsks, stripShip, type ShipRow } from './ship'; import { askMarkers, stripAsk, type AskRow, type CardClose } from './ask'; import { t } from './i18n'; @@ -409,7 +409,7 @@ export const CAPTAIN_STATUS: Record = { }; /** Where the Captain opens in Capy. */ -export const captainUrl = (id: string): string => `${CAPY_WEB}/thread/${id}`; +export const captainUrl = (id: string): string => `${capyWeb()}/thread/${id}`; /** * A message you sent that the Captain's transcript doesn't show yet. Capy lists a steered message only once the diff --git a/src/shared/capyLinks.test.ts b/src/shared/capyLinks.test.ts index 33d260b..b03062a 100644 --- a/src/shared/capyLinks.test.ts +++ b/src/shared/capyLinks.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { CAPY_API_SETTINGS, CAPY_THREADS, capyCodeOf, capyCodePage, capyCodeUrl, capyIssueUrl, capyPage } from './capyLinks'; +import { capyApiSettings, capyThreads, capyCodeOf, capyCodePage, capyCodeUrl, capyIssueUrl, capyPage } from './capyLinks'; import { parseMarkdown, type Block } from './markdown'; import { withRefs } from './refs'; @@ -25,7 +25,7 @@ describe('Capy links in agent text', () => { ['Captain code ORB-4', 'https://capy.ai/threads?code=ORB-4', 'https://capy.ai/thread/jam_01KCAPTAIN'], ['thread code HAL-4495', 'https://capy.ai/threads?code=HAL-4495', 'https://capy.ai/thread/jam_01KCREW'], ['issue code LUM-7302', 'https://capy.ai/threads?code=LUM-7302', 'https://capy.ai/issues/LUM-7302'], - ['unknown code ZZZ-1', 'https://capy.ai/threads?code=ZZZ-1', CAPY_THREADS], + ['unknown code ZZZ-1', 'https://capy.ai/threads?code=ZZZ-1', capyThreads()], ['PR #244', 'https://github.com/lumen/site/pull/244', 'https://github.com/lumen/site/pull/244'], ['commit b7ec2a8', 'https://github.com/lumen/site/commit/b7ec2a8', 'https://github.com/lumen/site/commit/b7ec2a8'], ['URL https://capy.ai/thread/jam_01KX', 'https://capy.ai/thread/jam_01KX', 'https://capy.ai/thread/jam_01KX'], @@ -75,26 +75,26 @@ describe('capyCodePage', () => { const resolve = vi.fn(async (c: string) => (c === 'ORB-901' ? { thread: 'jam_901' } : null)); expect(await capyCodePage('ORB-901', resolve)).toBe('https://capy.ai/thread/jam_901'); expect(await capyCodePage('ORB-901', resolve)).toBe('https://capy.ai/thread/jam_901'); - expect(await capyCodePage('NOPE-902', resolve)).toBe(CAPY_THREADS); - expect(await capyCodePage('NOPE-902', resolve)).toBe(CAPY_THREADS); + expect(await capyCodePage('NOPE-902', resolve)).toBe(capyThreads()); + expect(await capyCodePage('NOPE-902', resolve)).toBe(capyThreads()); expect(resolve).toHaveBeenCalledTimes(2); }); it('opens the threads list when the ask fails, and asks again next time', async () => { const resolve = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({ issue: 'LUM-903' }); - expect(await capyCodePage('LUM-903', resolve)).toBe(CAPY_THREADS); + expect(await capyCodePage('LUM-903', resolve)).toBe(capyThreads()); expect(await capyCodePage('LUM-903', resolve)).toBe('https://capy.ai/issues/LUM-903'); expect(resolve).toHaveBeenCalledTimes(2); }); it('opens the threads list without asking before yoji is connected', async () => { - expect(await capyCodePage('ORB-904', undefined)).toBe(CAPY_THREADS); + expect(await capyCodePage('ORB-904', undefined)).toBe(capyThreads()); }); }); describe('Capy API settings', () => { // Capy mints keys only under Settings → API (docs.capy.ai/api-reference/authentication), at capy.ai/settings/api. it('opens the page where Capy creates API keys', () => { - expect(CAPY_API_SETTINGS).toBe('https://capy.ai/settings/api'); + expect(capyApiSettings()).toBe('https://capy.ai/settings/api'); }); }); diff --git a/src/shared/capyLinks.ts b/src/shared/capyLinks.ts index 278a907..e406acc 100644 --- a/src/shared/capyLinks.ts +++ b/src/shared/capyLinks.ts @@ -3,25 +3,32 @@ // Capy's API never hands out thread codes. So a code links to a stand-in that yoji resolves when you open it, once per // code: capy:resolveCode asks Capy which issue or thread it is. The Mac and phone apps share this file. import { captainUrl } from './captains'; -import { CAPY_WEB } from './config'; +import { CAPY_WEB, capyWeb } from './config'; const CODE = /^[A-Z][A-Z0-9]{1,9}-\d+$/; -const STAND_IN = new RegExp(`^${CAPY_WEB.replace(/[./]/g, '\\$&')}/(?:threads\\?code=|thread/)([A-Za-z][A-Za-z0-9]{1,9}-\\d+)/?$`); +const standIn = (origin: string) => new RegExp(`^${origin.replace(/[./]/g, '\\$&')}/(?:threads\\?code=|thread/)([A-Za-z][A-Za-z0-9]{1,9}-\\d+)/?$`); +const STAND_IN = standIn(CAPY_WEB); /** Capy's threads list: where a code Capy can't place opens, rather than a "not found" page. */ -export const CAPY_THREADS = `${CAPY_WEB}/threads`; +export const capyThreads = (): string => `${capyWeb()}/threads`; /** Capy's Settings → API, where API keys are created. Capy shows a key only once, so a lost key is a new one made here. */ -export const CAPY_API_SETTINGS = `${CAPY_WEB}/settings/api`; +export const capyApiSettings = (): string => `${capyWeb()}/settings/api`; /** A Capy issue's page; the route takes the code itself. */ -export const capyIssueUrl = (code: string): string => `${CAPY_WEB}/issues/${code}`; +export const capyIssueUrl = (code: string): string => `${capyWeb()}/issues/${code}`; /** The link a code in agent text gets. Opened as is (copied, say), it lands on Capy's threads list. */ -export const capyCodeUrl = (code: string): string => `${CAPY_THREADS}?code=${code}`; +export const capyCodeUrl = (code: string): string => `${capyThreads()}?code=${code}`; -/** The code a capyCodeUrl link stands in for, or in a hand-written capy.ai/thread/ORB-4 link; null for any other link. */ -export const capyCodeOf = (url: string): string | null => STAND_IN.exec(url.trim())?.[1]?.toUpperCase() ?? null; +/** + * The code a capyCodeUrl link stands in for, or in a hand-written capy.ai/thread/ORB-4 link; null for any other link. + * Links on capy.ai always count, and so do links on the web address of the Capy server set in Settings (capyServer.ts). + */ +export function capyCodeOf(url: string): string | null { + const web = capyWeb(), text = url.trim(); + return (STAND_IN.exec(text) ?? (web === CAPY_WEB ? null : standIn(web).exec(text)))?.[1]?.toUpperCase() ?? null; +} /** Where Capy opens what capy:resolveCode found: the issue's page, the thread's page by its jam id, or null. */ export function capyPage(found: { issue: string } | { thread: string } | null): string | null { @@ -33,20 +40,20 @@ export function capyPage(found: { issue: string } | { thread: string } | null): const pages = new Map>(); /** - * The Capy page a code opens, asked of Capy once per code and kept for the session. An answer of "not one Capy knows" + * The Capy page a code opens, asked of Capy once per code (and Capy server) and kept for the session. An answer of "not one Capy knows" * is kept and opens the threads list; a failed ask (offline, Capy down) opens the threads list this time and asks again next time. */ export function capyCodePage(code: string, resolve: ((code: string) => Promise<{ issue: string } | { thread: string } | null>) | undefined): Promise { - const kept = pages.get(code); + const key = `${capyWeb()} ${code}`, kept = pages.get(key); if (kept) return kept; - if (!resolve || !CODE.test(code)) return Promise.resolve(CAPY_THREADS); + if (!resolve || !CODE.test(code)) return Promise.resolve(capyThreads()); const page = Promise.resolve(code).then(resolve).then( - (found) => capyPage(found) ?? CAPY_THREADS, + (found) => capyPage(found) ?? capyThreads(), () => { - pages.delete(code); - return CAPY_THREADS; + pages.delete(key); + return capyThreads(); }, ); - pages.set(code, page); + pages.set(key, page); return page; } diff --git a/src/shared/capyServer.test.ts b/src/shared/capyServer.test.ts new file mode 100644 index 0000000..d120732 --- /dev/null +++ b/src/shared/capyServer.test.ts @@ -0,0 +1,143 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { captainUrl } from './captains'; +import { capyApiSettings, capyCodeOf, capyCodePage, capyCodeUrl, capyIssueUrl, capyPage, capyThreads } from './capyLinks'; +import { capyHost, capyServerOf } from './capyServer'; +import { CAPY_API, CAPY_WEB, capyWeb, setCapyWeb } from './config'; +import { driveFileUrl, openDriveUrl } from './driveFiles'; +import { flightLink, flightSeek, type FlightGroup, type FlightRow } from './inFlight'; +import { parseMarkdown } from './markdown'; +import { withRefs } from './refs'; +import type { Captain } from './captains'; + +// The opt-in Capy server (Settings → Agents → Capy → Advanced). Empty, every link is what yoji built before it existed; +// set, every link is on its web address, and links on capy.ai still parse. example.com stands in for any other Capy. + +const SERVER = { web: 'https://capy.example.com', api: 'https://api.capy.example.com/api/v1' }; + +const captain: Captain = { id: 'cap1', name: 'Halcyon', color: '#5AAB6B', avatar: { emoji: '⚙️' }, status: 'working', needsYou: false, crewNeedsYou: 0, crewCount: 2, unread: false, lastActivityAt: 0 }; +const crewGroup: FlightGroup = { key: 'cap1', name: 'Halcyon', captain, rows: [] }; +const mineGroup: FlightGroup = { key: 'issues', name: 'Your tasks', issues: true, rows: [] }; +const issueRow: FlightRow = { key: 'iss1', title: 'Footer', status: 'working', summary: '', issue: { code: 'ORB-47', state: 'In progress' } }; +const threadRow: FlightRow = { key: 'jam_thread1', title: 'Footer', status: 'working', summary: '' }; +const linkOf = (text: string) => { + const [b] = withRefs(parseMarkdown(text), text); + return b?.kind === 'p' ? b.parts.flatMap((p) => (p.kind === 'link' ? [p.url] : []))[0] : undefined; +}; + +/** Every Capy page yoji builds, for one set of ids. */ +const everyLink = async () => ({ + captain: captainUrl('jam_1'), + issue: capyIssueUrl('ORB-47'), + threads: capyThreads(), + apiSettings: capyApiSettings(), + code: capyCodeUrl('ORB-4'), + pageIssue: capyPage({ issue: 'LUM-1' }), + pageThread: capyPage({ thread: 'jam_2' }), + codePage: await capyCodePage('ORB-905', async () => ({ thread: 'jam_905' })), + drivePersonal: driveFileUrl({ location: 'user-juniper', path: 'a.md' }), + driveOrg: driveFileUrl({ location: 'org-lumen', path: 'a.md' }), + driveProject: driveFileUrl({ location: 'project-orbit', path: 'a.md' }, [], [{ id: 'proj_1', name: 'Orbit' }]), + driveCaptain: driveFileUrl({ location: 'captain-halcyon', path: 'a.md' }, [{ id: 'jam_h', name: 'Halcyon' }]), + driveHome: driveFileUrl({ location: '', path: '' }), + driveOpened: await openDriveUrl({ location: 'project-orbit', path: 'b.md' }, [], { capyProjects: async () => [{ id: 'proj_1', name: 'Orbit' }] }), + flightIssue: flightLink(issueRow), + flightThread: flightLink(threadRow), + seekFallback: flightSeek(threadRow, crewGroup, []), + seekWeb: flightSeek(issueRow, mineGroup, []), + refCode: linkOf('See ORB-47 now'), +}); + +afterEach(() => setCapyWeb(null)); + +describe('the Capy server setting', () => { + it('empty, builds exactly the links yoji built before it existed', async () => { + expect(capyWeb()).toBe('https://capy.ai'); + expect(await everyLink()).toEqual({ + captain: 'https://capy.ai/thread/jam_1', + issue: 'https://capy.ai/issues/ORB-47', + threads: 'https://capy.ai/threads', + apiSettings: 'https://capy.ai/settings/api', + code: 'https://capy.ai/threads?code=ORB-4', + pageIssue: 'https://capy.ai/issues/LUM-1', + pageThread: 'https://capy.ai/thread/jam_2', + codePage: 'https://capy.ai/thread/jam_905', + drivePersonal: 'https://capy.ai/drive/personal?file=a.md', + driveOrg: 'https://capy.ai/drive/organization?file=a.md', + driveProject: 'https://capy.ai/project/proj_1/drive/shared?file=a.md', + driveCaptain: 'https://capy.ai/thread/jam_h?pane=drive-file%3Aa.md', + driveHome: 'https://capy.ai/drive', + driveOpened: 'https://capy.ai/project/proj_1/drive/shared?file=b.md', + flightIssue: 'https://capy.ai/issues/ORB-47', + flightThread: 'https://capy.ai/thread/jam_thread1', + seekFallback: { kind: 'captain', captainId: 'cap1', threads: ['jam_thread1'], fallback: 'https://capy.ai/thread/jam_thread1' }, + seekWeb: { kind: 'web', url: 'https://capy.ai/issues/ORB-47' }, + refCode: 'https://capy.ai/threads?code=ORB-47', + }); + setCapyWeb(''); + expect(capyWeb()).toBe(CAPY_WEB); + }); + + it('set, builds every link on the server’s web address', async () => { + setCapyWeb(SERVER.web); + const links = await everyLink(); + const urls = Object.values(links).flatMap((v) => (typeof v === 'string' ? [v] : v && typeof v === 'object' ? Object.values(v).filter((x): x is string => typeof x === 'string' && x.startsWith('http')) : [])); + expect(urls).toHaveLength(19); + for (const url of urls) expect(new URL(url).origin, url).toBe(SERVER.web); + expect(links.captain).toBe('https://capy.example.com/thread/jam_1'); + expect(links.driveOpened).toBe('https://capy.example.com/project/proj_1/drive/shared?file=b.md'); + expect(JSON.stringify(links)).not.toContain('capy.ai'); + }); + + it('set, reads codes in links on the server and on capy.ai, and on no other host', () => { + expect(capyCodeOf('https://capy.example.com/threads?code=ORB-4')).toBeNull(); + setCapyWeb(SERVER.web); + expect(capyCodeOf('https://capy.example.com/threads?code=ORB-4')).toBe('ORB-4'); + expect(capyCodeOf('https://capy.example.com/thread/orb-4')).toBe('ORB-4'); + expect(capyCodeOf('https://capy.ai/threads?code=ORB-4')).toBe('ORB-4'); + expect(capyCodeOf('https://capy.example.com.evil.example/threads?code=ORB-4')).toBeNull(); + expect(capyCodeOf('https://other.example.com/threads?code=ORB-4')).toBeNull(); + expect(capyCodeOf(capyCodeUrl('LUM-9'))).toBe('LUM-9'); + }); + + it('asks Capy again for a code once the server changes, so a page never opens on the wrong one', async () => { + let asked = 0; + const resolve = async () => (asked++, { issue: 'ORB-906' }); + expect(await capyCodePage('ORB-906', resolve)).toBe('https://capy.ai/issues/ORB-906'); + setCapyWeb(SERVER.web); + expect(await capyCodePage('ORB-906', resolve)).toBe('https://capy.example.com/issues/ORB-906'); + expect(asked).toBe(2); + }); +}); + +describe('capyServerOf: what the two fields accept', () => { + it('stores nothing when both are empty, or name Capy’s own servers', () => { + expect(capyServerOf('', '')).toEqual({ server: null }); + expect(capyServerOf(' ', ' ')).toEqual({ server: null }); + expect(capyServerOf('https://capy.ai/', `${CAPY_API}/`)).toEqual({ server: null }); + }); + + it('takes two https addresses, keeping the web origin and the API path without a trailing slash', () => { + expect(capyServerOf(' https://capy.example.com/ ', 'https://api.capy.example.com/api/v1/ ')).toEqual({ server: SERVER }); + expect(capyServerOf('https://capy.example.com:8443', 'https://capy.example.com:8443/api/v1')).toEqual({ server: { web: 'https://capy.example.com:8443', api: 'https://capy.example.com:8443/api/v1' } }); + }); + + it('wants both or neither', () => { + expect(capyServerOf(SERVER.web, '')).toEqual({ problem: 'both' }); + expect(capyServerOf('', SERVER.api)).toEqual({ problem: 'both' }); + }); + + it('takes only https, with no user, query or fragment', () => { + for (const bad of ['http://capy.example.com', 'capy.example.com', 'ftp://capy.example.com', 'javascript:alert(1)', 'https://user:pw@localhost', 'https://capy.example.com/?x=1', 'https://capy.example.com/#top', 'https://capy.example.com/?', 'not a url']) + expect(capyServerOf(bad, SERVER.api), bad).toEqual({ problem: 'https' }); + expect(capyServerOf(SERVER.web, 'http://api.capy.example.com/api/v1')).toEqual({ problem: 'https' }); + }); + + it('wants the web address without a path', () => { + expect(capyServerOf('https://capy.example.com/thread/jam_1', SERVER.api)).toEqual({ problem: 'web' }); + }); + + it('names a server by its host', () => { + expect(capyHost(SERVER.api)).toBe('api.capy.example.com'); + expect(capyHost(CAPY_API)).toBe('api.capy.ai'); + }); +}); diff --git a/src/shared/capyServer.ts b/src/shared/capyServer.ts new file mode 100644 index 0000000..f25c8d4 --- /dev/null +++ b/src/shared/capyServer.ts @@ -0,0 +1,53 @@ +// An opt-in Capy server, for a Capy environment other than production (Settings → Agents → Capy → Advanced). Empty, as +// it ships, yoji talks to Capy's own: pages and links on CAPY_WEB, and the API at CAPY_API_URL, else CAPY_API. Set, both +// come from it. Capy documents only production's pair (capy.ai, and api.capy.ai/api/v1 since the API moved off the web +// origin), so an API address can't be worked out from a web address, and the setting takes both. The Mac sets it with +// the key, and the phone follows what the Mac saved (agents:connections). Only https addresses are taken. +import { CAPY_API, CAPY_WEB } from './config'; + +export type CapyServer = { web: string; api: string }; + +/** Why a Capy server can't be saved: only one address given, not https, or a web address with a path. */ +export type CapyServerProblem = 'both' | 'https' | 'web'; + +/** The problems in words, for the backend's errors; the apps show their own translations (settings.agents.capyServer…). */ +export const CAPY_SERVER_PROBLEMS: Record = { + both: 'Give both the Capy web address and the Capy API address, or neither', + https: 'A Capy server address must be a full https:// address', + web: 'Give the Capy web address on its own, with no path', +}; + +/** An https address with nothing a server address shouldn't carry (a user name, query or fragment), or null. */ +function httpsUrl(text: string): URL | null { + try { + const u = new URL(text.trim()); + return u.protocol === 'https:' && !u.username && !u.password && !u.search && !u.hash && !text.trim().endsWith('?') && !text.trim().endsWith('#') ? u : null; + } catch { + return null; + } +} + +/** + * The Capy server two typed addresses name: null with both empty, or with production's own pair, so nothing is stored + * for Capy's own servers; a problem otherwise. The web address keeps only its origin and the API address loses any + * trailing slash, so yoji appends paths the same way it does to CAPY_API. + */ +export function capyServerOf(webText: string, apiText: string): { server: CapyServer | null } | { problem: CapyServerProblem } { + const webIn = webText.trim(), apiIn = apiText.trim(); + if (!webIn && !apiIn) return { server: null }; + if (!webIn || !apiIn) return { problem: 'both' }; + const w = httpsUrl(webIn), a = httpsUrl(apiIn); + if (!w || !a) return { problem: 'https' }; + if (w.pathname !== '/') return { problem: 'web' }; + const server = { web: w.origin, api: a.origin + a.pathname.replace(/\/+$/, '') }; + return server.web === CAPY_WEB && server.api === CAPY_API ? { server: null } : { server }; +} + +/** The host a Capy API address names, for errors that say which server answered. */ +export const capyHost = (api: string): string => { + try { + return new URL(api).host; + } catch { + return api; + } +}; diff --git a/src/shared/config.ts b/src/shared/config.ts index 457e9b7..30c8eb8 100644 --- a/src/shared/config.ts +++ b/src/shared/config.ts @@ -3,3 +3,20 @@ // own pages come from the deployment, with its connection (Connection.web). /** Capy's web app: threads, issues and Captain avatars. */ export const CAPY_WEB = 'https://capy.ai'; + +/** Capy's REST API, when neither the Capy connection's server (capyServer.ts) nor CAPY_API_URL names another. */ +export const CAPY_API = 'https://api.capy.ai/api/v1'; + +let web = CAPY_WEB; + +/** + * The Capy web app this app links to: CAPY_WEB, or the web address of the Capy server the connection was saved with + * (Settings → Agents → Capy → Advanced), which each app sets with setCapyWeb as the connection loads. Convex never sets + * it: what the backend builds takes the connection's own server (adapters/capy.ts). + */ +export const capyWeb = (): string => web; + +/** Points capyWeb at a Capy server's web address, or back at CAPY_WEB with none. */ +export function setCapyWeb(origin?: string | null): void { + web = origin || CAPY_WEB; +} diff --git a/src/shared/driveFiles.ts b/src/shared/driveFiles.ts index 868491b..c10804d 100644 --- a/src/shared/driveFiles.ts +++ b/src/shared/driveFiles.ts @@ -8,7 +8,7 @@ // The Mac and phone apps share this file. import { driveRef } from './ask'; import type { CaptainAttachment, CaptainMessage } from './captains'; -import { CAPY_WEB } from './config'; +import { capyWeb } from './config'; import { parseMarkdown, type Block, type Inline } from './markdown'; /** A drive file the chat knows of: where it lives in Capy Drive, and its copy on a message when a Captain delivered it. A folder's path ends in a slash. */ @@ -195,28 +195,30 @@ type Named = { id: string; name: string }; * Captain's in that Captain's file pane when `captains` has it, and anything else on the Drive page. */ export function driveFileUrl(f: Pick, captains: readonly Named[] = [], projects: readonly Named[] = []): string { - if (!f.location || !f.path) return `${CAPY_WEB}/drive`; + const web = capyWeb(); + if (!f.location || !f.path) return `${web}/drive`; const file = encodeURIComponent(f.path), loc = f.location.toLowerCase(); - if (loc.startsWith('user-')) return `${CAPY_WEB}/drive/personal?file=${file}`; - if (loc.startsWith('org-')) return `${CAPY_WEB}/drive/organization?file=${file}`; + if (loc.startsWith('user-')) return `${web}/drive/personal?file=${file}`; + if (loc.startsWith('org-')) return `${web}/drive/organization?file=${file}`; const mine = projects.find((p) => loc.startsWith(`project-user-${slug(p.name)}-`)); - if (mine) return `${CAPY_WEB}/project/${encodeURIComponent(mine.id)}/drive/personal?file=${file}`; + if (mine) return `${web}/project/${encodeURIComponent(mine.id)}/drive/personal?file=${file}`; const shared = projects.find((p) => loc === `project-${slug(p.name)}`); - if (shared) return `${CAPY_WEB}/project/${encodeURIComponent(shared.id)}/drive/shared?file=${file}`; + if (shared) return `${web}/project/${encodeURIComponent(shared.id)}/drive/shared?file=${file}`; const captain = loc.startsWith('captain-') ? captains.find((c) => `captain-${slug(c.name)}` === loc) : undefined; - if (captain) return `${CAPY_WEB}/thread/${encodeURIComponent(captain.id)}?pane=${encodeURIComponent(`drive-file:${f.path}`)}`; - return `${CAPY_WEB}/drive`; + if (captain) return `${web}/thread/${encodeURIComponent(captain.id)}?pane=${encodeURIComponent(`drive-file:${f.path}`)}`; + return `${web}/drive`; } -let projectList: Promise | null = null; +let projectList: { web: string; list: Promise } | null = null; /** * driveFileUrl for a file yoji opens: Capy's projects are asked for (capy:projects) only to open a project drive, once a - * session; a failed ask opens the Drive page this time and asks again next time. + * session for each Capy server; a failed ask opens the Drive page this time and asks again next time. */ export async function openDriveUrl(f: Pick, captains: readonly Named[], source: { capyProjects?: () => Promise } | null | undefined): Promise { if (!f.location?.toLowerCase().startsWith('project-') || !source?.capyProjects) return driveFileUrl(f, captains); - projectList ??= source.capyProjects().catch(() => ((projectList = null), [])); - return driveFileUrl(f, captains, await projectList); + const web = capyWeb(); + if (projectList?.web !== web) projectList = { web, list: source.capyProjects().catch(() => ((projectList = null), [])) }; + return driveFileUrl(f, captains, await projectList.list); } /** diff --git a/src/shared/i18n/locales/de/settings.ts b/src/shared/i18n/locales/de/settings.ts index 4852464..5dd6c8d 100644 --- a/src/shared/i18n/locales/de/settings.ts +++ b/src/shared/i18n/locales/de/settings.ts @@ -433,6 +433,16 @@ export default { 'settings.agents.capyKeyPlaceholder': 'Capy-API-Schlüssel einfügen', 'settings.agents.capyKeyOnce': 'Capy zeigt einen Schlüssel nur einmal an. Wenn du ihn nicht hast, erstelle in Capy unter Settings → API einen neuen Schlüssel und füge ihn hier ein.', 'settings.agents.capyOpenApi': 'Capy-API-Einstellungen öffnen', + 'settings.agents.capyAdvanced': 'Erweitert', + 'settings.agents.capyServer': 'Capy-Server', + 'settings.agents.capyServerDesc': 'Nur für eine Capy-Umgebung außerhalb der Produktion, etwa ein Staging-Capy. Lass beide Adressen leer, um Capy wie gewohnt zu nutzen.', + 'settings.agents.capyServerWeb': 'Webadresse', + 'settings.agents.capyServerApi': 'API-Adresse', + 'settings.agents.capyServerKey': 'Ein Schlüssel funktioniert nur auf dem Capy-Server, auf dem er erstellt wurde. Ein neuer Server braucht einen Schlüssel von diesem Server.', + 'settings.agents.capyServerUsing': 'Erweitert: Capy-Server {web}', + 'settings.agents.capyServerBoth': 'Gib die Webadresse und die API-Adresse an, oder keine von beiden.', + 'settings.agents.capyServerHttps': 'Verwende vollständige https://-Adressen.', + 'settings.agents.capyServerWebPath': 'Gib nur die Webadresse an, ohne Pfad.', 'settings.integrations.purpose.google': 'Termine aus deinen Kalendern, neben deinen Sessions.', 'settings.integrations.purpose.slack': 'Nachrichten, die dich erwähnen, landen im Posteingang.', 'settings.integrations.purpose.asana': 'Dir zugewiesene Aufgaben und Erwähnungen landen im Posteingang.', diff --git a/src/shared/i18n/locales/en/settings.ts b/src/shared/i18n/locales/en/settings.ts index 081b1e7..a7c2d44 100644 --- a/src/shared/i18n/locales/en/settings.ts +++ b/src/shared/i18n/locales/en/settings.ts @@ -430,6 +430,16 @@ export default { 'settings.agents.capyKeyPlaceholder': 'Paste your Capy API key', 'settings.agents.capyKeyOnce': 'Capy shows a key only once. If you don’t have it, create a new key in Capy under Settings → API and paste it here.', 'settings.agents.capyOpenApi': 'Open Capy API settings', + 'settings.agents.capyAdvanced': 'Advanced', + 'settings.agents.capyServer': 'Capy server', + 'settings.agents.capyServerDesc': 'Only for a non-production Capy environment, such as a staging Capy. Leave both addresses empty to use Capy as usual.', + 'settings.agents.capyServerWeb': 'Web address', + 'settings.agents.capyServerApi': 'API address', + 'settings.agents.capyServerKey': 'A key works only on the Capy server it was made on, so a new server needs a key from that server.', + 'settings.agents.capyServerUsing': 'Advanced: Capy server {web}', + 'settings.agents.capyServerBoth': 'Give both the web address and the API address, or neither.', + 'settings.agents.capyServerHttps': 'Use full https:// addresses.', + 'settings.agents.capyServerWebPath': 'Give the web address on its own, with no path.', 'settings.integrations.purpose.google': 'Events from your calendars, shown beside your sessions.', 'settings.integrations.purpose.slack': 'Messages that mention you land in Inbox.', 'settings.integrations.purpose.asana': 'Tasks assigned to you and mentions land in Inbox.', diff --git a/src/shared/i18n/locales/es/settings.ts b/src/shared/i18n/locales/es/settings.ts index c39dfb4..2af30ea 100644 --- a/src/shared/i18n/locales/es/settings.ts +++ b/src/shared/i18n/locales/es/settings.ts @@ -433,6 +433,16 @@ export default { 'settings.agents.capyKeyPlaceholder': 'Pega tu clave de API de Capy', 'settings.agents.capyKeyOnce': 'Capy muestra cada clave una sola vez. Si no la tienes, crea una clave nueva en Capy, en Settings → API, y pégala aquí.', 'settings.agents.capyOpenApi': 'Abrir los ajustes de API de Capy', + 'settings.agents.capyAdvanced': 'Avanzado', + 'settings.agents.capyServer': 'Servidor de Capy', + 'settings.agents.capyServerDesc': 'Solo para un entorno de Capy que no sea de producción, como un Capy de staging. Deja las dos direcciones vacías para usar Capy como siempre.', + 'settings.agents.capyServerWeb': 'Dirección web', + 'settings.agents.capyServerApi': 'Dirección de la API', + 'settings.agents.capyServerKey': 'Una clave solo funciona en el servidor de Capy donde se creó, así que un servidor nuevo necesita una clave de ese servidor.', + 'settings.agents.capyServerUsing': 'Avanzado: servidor de Capy {web}', + 'settings.agents.capyServerBoth': 'Indica la dirección web y la de la API, o ninguna.', + 'settings.agents.capyServerHttps': 'Usa direcciones https:// completas.', + 'settings.agents.capyServerWebPath': 'Indica solo la dirección web, sin ruta.', 'settings.integrations.purpose.google': 'Eventos de tus calendarios, junto a tus sesiones.', 'settings.integrations.purpose.slack': 'Los mensajes que te mencionan llegan a la bandeja de entrada.', 'settings.integrations.purpose.asana': 'Las tareas asignadas a ti y las menciones llegan a la bandeja de entrada.', diff --git a/src/shared/i18n/locales/fr/settings.ts b/src/shared/i18n/locales/fr/settings.ts index 9967800..55e6006 100644 --- a/src/shared/i18n/locales/fr/settings.ts +++ b/src/shared/i18n/locales/fr/settings.ts @@ -427,6 +427,16 @@ export default { 'settings.agents.capyKeyPlaceholder': 'Collez votre clé API Capy', 'settings.agents.capyKeyOnce': 'Capy n’affiche une clé qu’une seule fois. Si vous ne l’avez plus, créez une nouvelle clé dans Capy sous Settings → API et collez-la ici.', 'settings.agents.capyOpenApi': 'Ouvrir les réglages API de Capy', + 'settings.agents.capyAdvanced': 'Avancé', + 'settings.agents.capyServer': 'Serveur Capy', + 'settings.agents.capyServerDesc': 'Uniquement pour un environnement Capy hors production, comme un Capy de staging. Laissez les deux adresses vides pour utiliser Capy normalement.', + 'settings.agents.capyServerWeb': 'Adresse web', + 'settings.agents.capyServerApi': 'Adresse de l’API', + 'settings.agents.capyServerKey': 'Une clé ne fonctionne que sur le serveur Capy où elle a été créée : un nouveau serveur demande une clé de ce serveur.', + 'settings.agents.capyServerUsing': 'Avancé : serveur Capy {web}', + 'settings.agents.capyServerBoth': 'Indiquez l’adresse web et l’adresse de l’API, ou aucune des deux.', + 'settings.agents.capyServerHttps': 'Utilisez des adresses https:// complètes.', + 'settings.agents.capyServerWebPath': 'Indiquez l’adresse web seule, sans chemin.', 'settings.integrations.purpose.google': 'Les événements de vos calendriers, à côté de vos sessions.', 'settings.integrations.purpose.slack': 'Les messages qui vous mentionnent arrivent dans la boîte de réception.', 'settings.integrations.purpose.asana': 'Les tâches qui vous sont assignées et les mentions arrivent dans la boîte de réception.', diff --git a/src/shared/i18n/locales/ja/settings.ts b/src/shared/i18n/locales/ja/settings.ts index 03b7891..a55f866 100644 --- a/src/shared/i18n/locales/ja/settings.ts +++ b/src/shared/i18n/locales/ja/settings.ts @@ -434,6 +434,16 @@ export default { 'settings.agents.capyKeyPlaceholder': 'CapyのAPIキーを貼り付け', 'settings.agents.capyKeyOnce': 'Capy はキーを一度しか表示しません。手元にない場合は、Capy の Settings → API で新しいキーを作成し、ここに貼り付けてください。', 'settings.agents.capyOpenApi': 'Capy の API 設定を開く', + 'settings.agents.capyAdvanced': '詳細', + 'settings.agents.capyServer': 'Capy サーバー', + 'settings.agents.capyServerDesc': 'ステージングなど、本番以外の Capy 環境専用です。通常どおり Capy を使うときは、両方のアドレスを空のままにしてください。', + 'settings.agents.capyServerWeb': 'Web アドレス', + 'settings.agents.capyServerApi': 'API アドレス', + 'settings.agents.capyServerKey': 'キーは作成した Capy サーバーでのみ使えます。新しいサーバーにはそのサーバーのキーが必要です。', + 'settings.agents.capyServerUsing': '詳細:Capy サーバー {web}', + 'settings.agents.capyServerBoth': 'Web アドレスと API アドレスの両方を入力するか、両方を空にしてください。', + 'settings.agents.capyServerHttps': 'https:// から始まる完全なアドレスを使ってください。', + 'settings.agents.capyServerWebPath': 'Web アドレスはパスなしで入力してください。', 'settings.integrations.purpose.google': 'カレンダーの予定を、セッションの横に表示します。', 'settings.integrations.purpose.slack': 'あなたへのメンションを含むメッセージが受信トレイに届きます。', 'settings.integrations.purpose.asana': 'あなたに割り当てられたタスクとメンションが受信トレイに届きます。', diff --git a/src/shared/integrations.ts b/src/shared/integrations.ts index d934dd7..70b3483 100644 --- a/src/shared/integrations.ts +++ b/src/shared/integrations.ts @@ -14,6 +14,8 @@ import { FLIGHT_REFRESH, flightMessage, nextLeave, TASKS_UNREAD, withLeaving, ty import type { DraftEdit, DraftRow, DraftSync } from './draftSync'; import type { ItemReaction } from './inboxReactions'; import type { AgentConnection } from './agentAdapter'; +import type { CapyServer } from './capyServer'; +import { setCapyWeb } from './config'; import type { StartArgs, StartResult, UploadArgs, UploadResult } from './newChat'; import { byStartThenLongest } from './layout'; import type { CapyModelList, ModelChoice, ModelDefaults } from './capyModels'; @@ -225,7 +227,7 @@ const refs = { pinChat: makeFunctionReference<'mutation', ChatRef & { pinned: boolean }, null>('agents:pin'), linkChat: makeFunctionReference<'mutation', ChatRef & { taskId: string | null }, null>('agents:setTask'), startConnect: makeFunctionReference<'mutation', { provider: Provider }, { url: string }>('integrations:startConnect'), - connectCapy: makeFunctionReference<'action', { apiKey: string }, null>('agents:connectCapy'), + connectCapy: makeFunctionReference<'action', { apiKey: string; server?: CapyServer }, null>('agents:connectCapy'), disconnectCapy: makeFunctionReference<'mutation', NoArgs, null>('agents:disconnectCapy'), disconnect: makeFunctionReference<'mutation', { id: string }, unknown>('integrations:disconnect'), setCalendar: makeFunctionReference<'mutation', { id: string; enabled?: boolean; color?: string }, unknown>('integrations:setCalendar'), @@ -330,7 +332,8 @@ export interface IntegrationsSource { /** Asks the backend for the provider's authorize URL and opens it with the app's `open`. */ startConnect(provider: Provider): Promise; /** Connects Capy with an API key, which the backend checks with Capy and stores encrypted (Settings → Agents). */ - connectCapy(apiKey: string): Promise; + /** `server`: the Capy server from Settings → Agents → Capy → Advanced, sent only when one is set (src/shared/capyServer.ts). */ + connectCapy(apiKey: string, server?: CapyServer): Promise; disconnectCapy(): Promise; disconnect(id: string): Promise; setCalendar(id: string, patch: { enabled?: boolean; color?: string }): Promise; @@ -661,7 +664,7 @@ export function connectIntegrations(url: string, open: (url: string) => unknown) subscribe(sendable(args)); return () => off(); }, - connectCapy: (apiKey) => client.action(refs.connectCapy, { apiKey }), + connectCapy: (apiKey, server) => client.action(refs.connectCapy, server ? { apiKey, server } : { apiKey }), disconnectCapy: () => client.mutation(refs.disconnectCapy, {}), startConnect: async (provider) => { const { url: authorize } = await client.mutation(refs.startConnect, { provider }); @@ -1044,6 +1047,15 @@ export function useAgentConnectionsFrom(source: IntegrationsSource | null): Agen return useWatch(source, 'agents:connections', {}).value ?? null; } +/** + * Points this app's Capy links (capyWeb) at the Capy server the connection was saved with, or at capy.ai with none, + * once the connections list arrives. Each app calls it at its root, so every link built after that uses the server. + */ +export function useCapyWebFrom(source: IntegrationsSource | null): void { + const connections = useAgentConnectionsFrom(source); + if (connections) setCapyWeb(connections.find((c) => c.kind === 'capy')?.server?.web); +} + /** * The agents panel: your Capy chats, newest first, reread from Capy at the Captains list's pace while the panel * is on screen and the app visible (one capyChats:refresh each CAPTAINS_REFRESH); nothing rereads them otherwise.