diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index ecbc4d61..4d68ca15 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -1,8 +1,23 @@ import { z } from 'zod' -import { ASSISTANT_NOTIFICATION_LIMITS, MANAGER_TOOL_ACTIONS, MANAGER_TOOL_NAME, ShowArtifactParamsSchema, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas' +import { + ASSISTANT_NOTIFICATION_LIMITS, + MANAGER_PROMPT_CLIENT_METADATA_KEY, + MANAGER_PROMPT_CLIENTS, + MANAGER_TOOL_ACTIONS, + MANAGER_TOOL_NAME, + ShowArtifactParamsSchema, + WalkthroughSourceSchema, +} from '@opencode-manager/shared/schemas' const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 60000 +const MOBILE_PROMPT_CLIENT = MANAGER_PROMPT_CLIENTS[0] + +const DESKTOP_PROMPT_CLIENT = MANAGER_PROMPT_CLIENTS[1] + +export const MANAGER_MOBILE_OUTPUT_INSTRUCTIONS = + 'The user is on a mobile device and may listen to your replies with text-to-speech. Write replies as short, plain, conversational sentences that read well aloud. Avoid tables, headings, code blocks, long or nested lists, file paths, URLs, and raw symbols unless the user explicitly asks for them; describe technical details in words instead. Lead with the outcome and keep it brief. This only changes how you write replies, not how thoroughly you work or use tools.' + export const MANAGER_TOOL_ALLOWED_ROUTES = [ 'GET /settings', 'PATCH /settings', @@ -149,6 +164,31 @@ var INPUT_SCHEMA = ${JSON.stringify(buildManagerToolInputJsonSchema(), null, 2)} var DESCRIPTION = ${JSON.stringify(buildManagerToolDescription())} +var CLIENT_METADATA_KEY = ${JSON.stringify(MANAGER_PROMPT_CLIENT_METADATA_KEY)} + +var MOBILE_CLIENT = ${JSON.stringify(MOBILE_PROMPT_CLIENT)} + +var DESKTOP_CLIENT = ${JSON.stringify(DESKTOP_PROMPT_CLIENT)} + +var MOBILE_OUTPUT_INSTRUCTIONS = ${JSON.stringify(MANAGER_MOBILE_OUTPUT_INSTRUCTIONS)} + +var MOBILE_SESSIONS = new Set() + +function trackMobileSession(event) { + var client = event.metadata && event.metadata[CLIENT_METADATA_KEY] + if (client === MOBILE_CLIENT) { + MOBILE_SESSIONS.add(event.sessionID) + } else if (client === DESKTOP_CLIENT) { + MOBILE_SESSIONS.delete(event.sessionID) + } +} + +function addMobileOutputInstructions(event) { + if (MOBILE_SESSIONS.has(event.sessionID)) { + event.system.push({ type: 'text', text: MOBILE_OUTPUT_INSTRUCTIONS }) + } +} + function resolveRoute(path) { var baseUrl = process.env.OCM_INTERNAL_API_URL var token = process.env.OCM_INTERNAL_TOKEN @@ -290,6 +330,8 @@ async function runAction(input, context) { export default { id: '${id}', async setup(ctx) { + await ctx.session.hook('prompt', trackMobileSession) + await ctx.session.hook('context', addMobileOutputInstructions) await ctx.tool.transform(function (editor) { editor.add({ name: ${JSON.stringify(MANAGER_TOOL_NAME)}, diff --git a/backend/test/helpers/opencode-plugin-context.ts b/backend/test/helpers/opencode-plugin-context.ts index 8ba18cb4..d26f8847 100644 --- a/backend/test/helpers/opencode-plugin-context.ts +++ b/backend/test/helpers/opencode-plugin-context.ts @@ -38,17 +38,40 @@ export type PermissionEvaluateEvent = { [key: string]: unknown } +export type SessionPromptEvent = { + sessionID: string + prompt?: unknown + metadata?: Record + [key: string]: unknown +} + +export type SessionContextEvent = { + sessionID: string + agent?: unknown + model?: unknown + system: Array<{ type: string; text: string; [key: string]: unknown }> + messages?: unknown + tools?: unknown + options?: unknown + [key: string]: unknown +} + export type GeneratedPlugin = { id: string triggerShellCreateBefore: (event: ShellCreateBeforeEvent) => Promise triggerToolExecuteAfter: (event: ToolExecuteAfterEvent) => Promise triggerPermissionEvaluate: (event: PermissionEvaluateEvent) => Promise + triggerSessionPrompt: (event: SessionPromptEvent) => Promise + triggerSessionContext: (event: SessionContextEvent) => Promise registeredTools: () => GeneratedTool[] } type ShellHookCallback = (event: ShellCreateBeforeEvent) => Promise | void type ToolHookCallback = (event: ToolExecuteAfterEvent) => Promise | void type PermissionHookCallback = (event: PermissionEvaluateEvent) => Promise | void +type SessionPromptHookCallback = (event: SessionPromptEvent) => Promise | void +type SessionContextHookCallback = (event: SessionContextEvent) => Promise | void +type SessionHookCallback = SessionPromptHookCallback | SessionContextHookCallback type ToolTransformCallback = (editor: { add: (tool: GeneratedTool) => void }) => void type Registration = { dispose: () => Promise } @@ -64,6 +87,9 @@ type PluginContext = { permission: { hook: (name: string, callback: PermissionHookCallback) => Promise } + session: { + hook: (name: string, callback: SessionHookCallback) => Promise + } } function createRegistry(name: string) { @@ -84,6 +110,8 @@ function createPluginContext() { const shellCreateBefore = createRegistry('create.before') const toolExecuteAfter = createRegistry('execute.after') const permissionEvaluate = createRegistry('evaluate') + const sessionPrompt = createRegistry('prompt') + const sessionContext = createRegistry('context') const transforms: ToolTransformCallback[] = [] const context: PluginContext = { @@ -109,6 +137,13 @@ function createPluginContext() { return permissionEvaluate.register(callback) }, }, + session: { + hook: async (name, callback) => { + if (name === 'prompt') return sessionPrompt.register(callback as SessionPromptHookCallback) + if (name === 'context') return sessionContext.register(callback as SessionContextHookCallback) + throw new Error(`unexpected session hook ${name}`) + }, + }, } return { @@ -116,6 +151,8 @@ function createPluginContext() { triggerShellCreateBefore: (event: ShellCreateBeforeEvent) => shellCreateBefore.trigger(event), triggerToolExecuteAfter: (event: ToolExecuteAfterEvent) => toolExecuteAfter.trigger(event), triggerPermissionEvaluate: (event: PermissionEvaluateEvent) => permissionEvaluate.trigger(event), + triggerSessionPrompt: (event: SessionPromptEvent) => sessionPrompt.trigger(event), + triggerSessionContext: (event: SessionContextEvent) => sessionContext.trigger(event), registeredTools: () => { const tools: GeneratedTool[] = [] const editor = { add: (tool: GeneratedTool) => tools.push(tool) } @@ -150,6 +187,8 @@ export async function loadGeneratedPlugin(file: string): Promise { + return loadGeneratedPlugin(path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js')) +} + async function loadTool(configHome: string): Promise { const plugin = await loadGeneratedPlugin(path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js')) const tool = plugin.registeredTools().find((candidate) => candidate.name === MANAGER_TOOL_NAME) @@ -97,6 +110,50 @@ describe('ocm-manager plugin', () => { expect(plugin.id).toBe('ocm.manager') }) + describe('mobile output instructions', () => { + it('adds the mobile output instructions to a session prompted from the mobile client', async () => { + const plugin = await loadManagerPlugin(configHome) + await plugin.triggerSessionPrompt({ sessionID: 'ses_mobile', metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: 'mobile' } }) + const event: SessionContextEvent = { sessionID: 'ses_mobile', system: [] } + + await plugin.triggerSessionContext(event) + + expect(event.system).toEqual([{ type: 'text', text: MANAGER_MOBILE_OUTPUT_INSTRUCTIONS }]) + }) + + it('removes the mobile output instructions when the latest prompt is from the desktop client', async () => { + const plugin = await loadManagerPlugin(configHome) + await plugin.triggerSessionPrompt({ sessionID: 'ses_switch', metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: 'mobile' } }) + await plugin.triggerSessionPrompt({ sessionID: 'ses_switch', metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: 'desktop' } }) + const event: SessionContextEvent = { sessionID: 'ses_switch', system: [] } + + await plugin.triggerSessionContext(event) + + expect(event.system).toEqual([]) + }) + + it('keeps the mobile output instructions when a later prompt carries no client metadata', async () => { + const plugin = await loadManagerPlugin(configHome) + await plugin.triggerSessionPrompt({ sessionID: 'ses_nometa', metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: 'mobile' } }) + await plugin.triggerSessionPrompt({ sessionID: 'ses_nometa' }) + const event: SessionContextEvent = { sessionID: 'ses_nometa', system: [] } + + await plugin.triggerSessionContext(event) + + expect(event.system).toEqual([{ type: 'text', text: MANAGER_MOBILE_OUTPUT_INSTRUCTIONS }]) + }) + + it('leaves sessions prompted from another client without the mobile output instructions', async () => { + const plugin = await loadManagerPlugin(configHome) + await plugin.triggerSessionPrompt({ sessionID: 'ses_mobile', metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: 'mobile' } }) + const event: SessionContextEvent = { sessionID: 'ses_other', system: [] } + + await plugin.triggerSessionContext(event) + + expect(event.system).toEqual([]) + }) + }) + it('writes a plugin file with no zod import and no import statement', async () => { const source = await fs.readFile(path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js'), 'utf-8') diff --git a/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts index 99d4542e..0d9d01ed 100644 --- a/frontend/src/api/opencode.test.ts +++ b/frontend/src/api/opencode.test.ts @@ -58,6 +58,7 @@ describe('OpenCode facade', () => { afterEach(() => { vi.unstubAllGlobals() + vi.restoreAllMocks() }) const lastRequest = () => { @@ -268,7 +269,7 @@ describe('OpenCode facade', () => { const [promptUrl, promptInit] = fetchMock.mock.calls[1] ?? [] expect(String(promptUrl)).toBe('http://localhost/api/opencode/api/session/ses_new/prompt') expect((promptInit as RequestInit).method).toBe('POST') - expect((promptInit as RequestInit).body).toBe(JSON.stringify({ text: 'Fix conflicts' })) + expect((promptInit as RequestInit).body).toBe(JSON.stringify({ text: 'Fix conflicts', metadata: { ocmClient: 'desktop' } })) }) it('deletes the new session when sending the prompt fails', async () => { @@ -477,11 +478,56 @@ describe('OpenCode facade', () => { files: [{ uri: 'file:///repo/src/a.ts', name: 'a.ts', mention: { start: 6, end: 15, text: '@src/a.ts' } }], agents: [{ name: 'build', mention: { start: 6, end: 12, text: '@build' } }], skills: [{ id: 'review' }], + metadata: { ocmClient: 'desktop' }, delivery: 'queue', })) expect(inbox.id).toBe('msg_1') }) + it('marks a prompt as mobile when the viewport is narrow', async () => { + vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(375) + fetchMock.mockResolvedValue( + jsonResponse({ + data: { + id: 'msg_1', + sessionID: 'ses_1', + time: { created: 1000 }, + type: 'user', + payload: { text: 'Hi' }, + }, + }), + ) + + await sendPrompt({ sessionID: 'ses_1', text: 'Hi' }) + + expect(lastRequest().init.body).toBe(JSON.stringify({ + text: 'Hi', + metadata: { ocmClient: 'mobile' }, + })) + }) + + it('marks a prompt as desktop when the viewport is wide', async () => { + vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(1280) + fetchMock.mockResolvedValue( + jsonResponse({ + data: { + id: 'msg_1', + sessionID: 'ses_1', + time: { created: 1000 }, + type: 'user', + payload: { text: 'Hi' }, + }, + }), + ) + + await sendPrompt({ sessionID: 'ses_1', text: 'Hi' }) + + expect(lastRequest().init.body).toBe(JSON.stringify({ + text: 'Hi', + metadata: { ocmClient: 'desktop' }, + })) + }) + it('switches the session model through the V2 model route', async () => { fetchMock.mockResolvedValue(new Response(null, { status: 204 })) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 35de78f0..9d96c2f7 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -1,4 +1,6 @@ import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode' +import { MANAGER_PROMPT_CLIENT_METADATA_KEY } from '@opencode-manager/shared/schemas' +import { isMobileViewport } from '@/hooks/useMobile' import { callOpenCode } from './opencodeApi' import type { AgentInfo, @@ -186,6 +188,7 @@ export async function sendPrompt(input: SendPromptInput): Promise (typeof window !== 'undefined' ? window.innerWidth < 768 : false)) + const [isMobile, setIsMobile] = useState(isMobileViewport) useEffect(() => { const checkMobile = () => { - setIsMobile(window.innerWidth < 768) + setIsMobile(isMobileViewport()) } checkMobile() diff --git a/shared/src/schemas/internal-assistant.ts b/shared/src/schemas/internal-assistant.ts index bd3c6a1d..7b10b7a9 100644 --- a/shared/src/schemas/internal-assistant.ts +++ b/shared/src/schemas/internal-assistant.ts @@ -3,6 +3,12 @@ import { UserPreferencesSchema } from './settings' export const MANAGER_TOOL_NAME = 'ocm' +export const MANAGER_PROMPT_CLIENT_METADATA_KEY = 'ocmClient' + +export const MANAGER_PROMPT_CLIENTS = ['mobile', 'desktop'] as const + +export type ManagerPromptClient = (typeof MANAGER_PROMPT_CLIENTS)[number] + export const MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION = 'open_walkthrough' export const MANAGER_TOOL_SHOW_ARTIFACT_ACTION = 'show_artifact'