From b974618deeea9143b1ada7252982efb0187b2b8b Mon Sep 17 00:00:00 2001 From: Chris Scott <> Date: Wed, 14 Oct 2026 20:38:54 +0000 Subject: [PATCH 1/2] feat(chat): tailor replies for mobile and text-to-speech --- .../services/opencode-manager-tool-plugin.ts | 44 ++++++++++++- .../test/helpers/opencode-plugin-context.ts | 39 ++++++++++++ .../opencode-manager-tool-plugin.test.ts | 63 ++++++++++++++++++- frontend/src/api/opencode.test.ts | 48 +++++++++++++- frontend/src/api/opencode.ts | 3 + frontend/src/hooks/useMobile.ts | 8 ++- shared/src/schemas/internal-assistant.ts | 6 ++ 7 files changed, 204 insertions(+), 7 deletions(-) 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' From f80aa1c0e57c10f05062320587134aad36b8331c Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:06:19 +0000 Subject: [PATCH 2/2] docs: document mobile session hooks, plugin test helpers, and viewport detection --- backend/src/services/opencode-manager-tool-plugin.ts | 4 ++++ backend/test/helpers/opencode-plugin-context.ts | 5 +++++ backend/test/services/opencode-manager-tool-plugin.test.ts | 1 + frontend/src/api/opencode.ts | 1 + frontend/src/hooks/useMobile.ts | 3 +++ 5 files changed, 14 insertions(+) diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index 4d68ca15..c48758c9 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -147,6 +147,7 @@ function buildManagerToolDescription(): string { .join('\n') } +/** Builds the standalone manager plugin with API actions and mobile session hooks. */ export function buildManagerToolPluginSource(id: string): string { return `var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS} @@ -174,6 +175,7 @@ var MOBILE_OUTPUT_INSTRUCTIONS = ${JSON.stringify(MANAGER_MOBILE_OUTPUT_INSTRUCT var MOBILE_SESSIONS = new Set() +/** Updates mobile mode from explicit client metadata, preserving it when metadata is absent. */ function trackMobileSession(event) { var client = event.metadata && event.metadata[CLIENT_METADATA_KEY] if (client === MOBILE_CLIENT) { @@ -183,6 +185,7 @@ function trackMobileSession(event) { } } +/** Appends mobile reply guidance to the context of a tracked mobile session. */ function addMobileOutputInstructions(event) { if (MOBILE_SESSIONS.has(event.sessionID)) { event.system.push({ type: 'text', text: MOBILE_OUTPUT_INSTRUCTIONS }) @@ -329,6 +332,7 @@ async function runAction(input, context) { export default { id: '${id}', + /** Registers session hooks and exposes the manager tool through the plugin context. */ async setup(ctx) { await ctx.session.hook('prompt', trackMobileSession) await ctx.session.hook('context', addMobileOutputInstructions) diff --git a/backend/test/helpers/opencode-plugin-context.ts b/backend/test/helpers/opencode-plugin-context.ts index d26f8847..6d9fbbbc 100644 --- a/backend/test/helpers/opencode-plugin-context.ts +++ b/backend/test/helpers/opencode-plugin-context.ts @@ -106,6 +106,7 @@ function createRegistry(name: string) { } } +/** Creates a test plugin context with hook registries, event triggers, and tool transforms. */ function createPluginContext() { const shellCreateBefore = createRegistry('create.before') const toolExecuteAfter = createRegistry('execute.after') @@ -138,6 +139,7 @@ function createPluginContext() { }, }, session: { + /** Registers prompt or context callbacks, rejecting unsupported session hook names. */ hook: async (name, callback) => { if (name === 'prompt') return sessionPrompt.register(callback as SessionPromptHookCallback) if (name === 'context') return sessionContext.register(callback as SessionContextHookCallback) @@ -151,7 +153,9 @@ function createPluginContext() { triggerShellCreateBefore: (event: ShellCreateBeforeEvent) => shellCreateBefore.trigger(event), triggerToolExecuteAfter: (event: ToolExecuteAfterEvent) => toolExecuteAfter.trigger(event), triggerPermissionEvaluate: (event: PermissionEvaluateEvent) => permissionEvaluate.trigger(event), + /** Dispatches a prompt event to the registered session callbacks. */ triggerSessionPrompt: (event: SessionPromptEvent) => sessionPrompt.trigger(event), + /** Dispatches a context event so registered callbacks can update it. */ triggerSessionContext: (event: SessionContextEvent) => sessionContext.trigger(event), registeredTools: () => { const tools: GeneratedTool[] = [] @@ -164,6 +168,7 @@ function createPluginContext() { let importCount = 0 +/** Imports a fresh plugin instance, validates its definition, and runs setup in the test context. */ export async function loadGeneratedPlugin(file: string): Promise { importCount += 1 const imported = (await import(`${pathToFileURL(file).href}?ocm-test=${importCount}`)) as { default?: unknown } diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index b1142fe3..65c3e590 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -33,6 +33,7 @@ type JsonSchema = { minLength?: number } +/** Loads the installed manager plugin from the supplied configuration home for hook tests. */ async function loadManagerPlugin(configHome: string): Promise { return loadGeneratedPlugin(path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js')) } diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 9d96c2f7..0630b25d 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -183,6 +183,7 @@ export async function switchSessionAgent(sessionID: string, agent: string): Prom await callOpenCode((api) => api.session.switchAgent({ sessionID, agent })) } +/** Sends a session prompt with client metadata derived from the current viewport. */ export async function sendPrompt(input: SendPromptInput): Promise { return callOpenCode((api) => api.session.prompt({ diff --git a/frontend/src/hooks/useMobile.ts b/frontend/src/hooks/useMobile.ts index 56e600cc..63b7ceb6 100644 --- a/frontend/src/hooks/useMobile.ts +++ b/frontend/src/hooks/useMobile.ts @@ -1,14 +1,17 @@ import { useState, useEffect, useCallback, useRef, type CSSProperties } from 'react' import { useSwipeNavigation } from '@/contexts/SwipeNavigationContext' +/** Returns whether the viewport is narrower than 768 pixels, or false without a browser window. */ export function isMobileViewport(): boolean { return typeof window !== 'undefined' ? window.innerWidth < 768 : false } +/** Tracks whether the current viewport is mobile, updating the value on window resize. */ export function useMobile() { const [isMobile, setIsMobile] = useState(isMobileViewport) useEffect(() => { + /** Refreshes the mobile state from the current viewport width. */ const checkMobile = () => { setIsMobile(isMobileViewport()) }