feat(chat): tailor replies for mobile and text-to-speech

This commit is contained in:
Chris Scott committed 2026-10-14 20:38:54 +00:00
1 parent b140a9c77b
commit b974618dee
7 files changed
+204 -7

No files matched your search

@@ -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)},
@@ -38,17 +38,40 @@ export type PermissionEvaluateEvent = {
[key: string]: unknown
}
export type SessionPromptEvent = {
sessionID: string
prompt?: unknown
metadata?: Record<string, unknown>
[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<void>
triggerToolExecuteAfter: (event: ToolExecuteAfterEvent) => Promise<void>
triggerPermissionEvaluate: (event: PermissionEvaluateEvent) => Promise<void>
triggerSessionPrompt: (event: SessionPromptEvent) => Promise<void>
triggerSessionContext: (event: SessionContextEvent) => Promise<void>
registeredTools: () => GeneratedTool[]
}
type ShellHookCallback = (event: ShellCreateBeforeEvent) => Promise<void> | void
type ToolHookCallback = (event: ToolExecuteAfterEvent) => Promise<void> | void
type PermissionHookCallback = (event: PermissionEvaluateEvent) => Promise<void> | void
type SessionPromptHookCallback = (event: SessionPromptEvent) => Promise<void> | void
type SessionContextHookCallback = (event: SessionContextEvent) => Promise<void> | void
type SessionHookCallback = SessionPromptHookCallback | SessionContextHookCallback
type ToolTransformCallback = (editor: { add: (tool: GeneratedTool) => void }) => void
type Registration = { dispose: () => Promise<void> }
@@ -64,6 +87,9 @@ type PluginContext = {
permission: {
hook: (name: string, callback: PermissionHookCallback) => Promise<Registration>
}
session: {
hook: (name: string, callback: SessionHookCallback) => Promise<Registration>
}
}
function createRegistry<Event>(name: string) {
@@ -84,6 +110,8 @@ function createPluginContext() {
const shellCreateBefore = createRegistry<ShellCreateBeforeEvent>('create.before')
const toolExecuteAfter = createRegistry<ToolExecuteAfterEvent>('execute.after')
const permissionEvaluate = createRegistry<PermissionEvaluateEvent>('evaluate')
const sessionPrompt = createRegistry<SessionPromptEvent>('prompt')
const sessionContext = createRegistry<SessionContextEvent>('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<GeneratedPlugin
triggerShellCreateBefore: registrations.triggerShellCreateBefore,
triggerToolExecuteAfter: registrations.triggerToolExecuteAfter,
triggerPermissionEvaluate: registrations.triggerPermissionEvaluate,
triggerSessionPrompt: registrations.triggerSessionPrompt,
triggerSessionContext: registrations.triggerSessionContext,
registeredTools: registrations.registeredTools,
}
}
@@ -5,10 +5,19 @@ import http from 'http'
import type { AddressInfo } from 'net'
import path from 'path'
import os from 'os'
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantNotificationRequestSchema, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas'
import { MANAGER_TOOL_ALLOWED_ROUTES, parseAllowedRoute } from '../../src/services/opencode-manager-tool-plugin'
import {
ASSISTANT_NOTIFICATION_LIMITS,
AssistantNotificationRequestSchema,
MANAGER_PROMPT_CLIENT_METADATA_KEY,
MANAGER_TOOL_NAME,
} from '@opencode-manager/shared/schemas'
import {
MANAGER_MOBILE_OUTPUT_INSTRUCTIONS,
MANAGER_TOOL_ALLOWED_ROUTES,
parseAllowedRoute,
} from '../../src/services/opencode-manager-tool-plugin'
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
import { loadGeneratedPlugin, type GeneratedTool } from '../helpers/opencode-plugin-context'
import { loadGeneratedPlugin, type GeneratedPlugin, type GeneratedTool, type SessionContextEvent } from '../helpers/opencode-plugin-context'
import { resolveOpenCode2Binary, runOpenCodeStandalone } from '../helpers/opencode-binary'
type JsonSchema = {
@@ -24,6 +33,10 @@ type JsonSchema = {
minLength?: number
}
async function loadManagerPlugin(configHome: string): Promise<GeneratedPlugin> {
return loadGeneratedPlugin(path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js'))
}
async function loadTool(configHome: string): Promise<GeneratedTool> {
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')
+47 -1
View File
@@ -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 }))
+3
View File
@@ -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<SessionInboxUs
api.session.prompt({
sessionID: input.sessionID,
...buildPromptFields(input),
metadata: { [MANAGER_PROMPT_CLIENT_METADATA_KEY]: isMobileViewport() ? 'mobile' : 'desktop' },
}),
)
}
+6 -2
View File
@@ -1,12 +1,16 @@
import { useState, useEffect, useCallback, useRef, type CSSProperties } from 'react'
import { useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
export function isMobileViewport(): boolean {
return typeof window !== 'undefined' ? window.innerWidth < 768 : false
}
export function useMobile() {
const [isMobile, setIsMobile] = useState(() => (typeof window !== 'undefined' ? window.innerWidth < 768 : false))
const [isMobile, setIsMobile] = useState(isMobileViewport)
useEffect(() => {
const checkMobile = () => {
setIsMobile(window.innerWidth < 768)
setIsMobile(isMobileViewport())
}
checkMobile()
+6
View File
@@ -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'