feat(opencode): slash command support (#671) (#753)

This commit is contained in:
SSU-WEI HUANG
2026-05-31 19:35:31 +08:00
committed by GitHub
parent 31dd4353d4
commit 5b797bb95d
17 changed files with 775 additions and 28 deletions
+125 -11
View File
@@ -1,4 +1,5 @@
import { logger } from '@/ui/logger';
import { randomUUID } from 'node:crypto';
import { opencodeLoop } from './loop';
import { MessageQueue2 } from '@/utils/MessageQueue2';
import { hashObject } from '@/utils/deterministicJson';
@@ -13,6 +14,8 @@ import { registerSessionConfigRpc } from '@/agent/sessionConfigRpc';
import { startOpencodeHookServer } from './utils/startOpencodeHookServer';
import { formatMessageWithAttachments } from '@/utils/attachmentFormatter';
import { getInvokedCwd } from '@/utils/invokedCwd';
import { listSlashCommands } from '@/modules/common/slashCommands';
import { resolveOpencodeSlashCommand } from './utils/slashCommands';
export async function runOpencode(opts: {
startedBy?: 'runner' | 'terminal';
@@ -72,7 +75,10 @@ export async function runOpencode(opts: {
const messageQueue = new MessageQueue2<OpencodeMode>((mode) => hashObject({
permissionMode: mode.permissionMode,
model: mode.model ?? null,
// Distinguish "explicit reset" (null) from "no change" (undefined) so
// batches with different intent don't merge — the launcher uses null
// to mean "switch back to defaultBackendModel".
model: mode.model === null ? '__reset__' : mode.model ?? null,
modelReasoningEffort: mode.modelReasoningEffort ?? null
}));
@@ -120,20 +126,128 @@ export async function runOpencode(opts: {
logger.debug(`[opencode] Synced session config for keepalive: permissionMode=${currentPermissionMode}, model=${sessionModel ?? '(default)'}, modelReasoningEffort=${sessionModelReasoningEffort ?? '(default)'}`);
};
// Slash-command resolution now runs inside an async chain on
// `session.onUserMessage`, so there is a window between the message
// arriving and `messageQueue.push` / `sendAgentMessage` where
// `cancelByLocalId` would find nothing. Track in-flight localIds so the
// cancel RPC can ack the cancel during that window and the chain can
// short-circuit when it resumes.
const preparingLocalIds = new Set<string>();
const cancelledBeforeEnqueue = new Set<string>();
let userMessageChain: Promise<void> = Promise.resolve();
session.onUserMessage((message, localId) => {
const formattedText = formatMessageWithAttachments(message.content.text, message.content.attachments);
const mode: OpencodeMode = {
permissionMode: currentPermissionMode,
model: sessionModel ?? undefined,
modelReasoningEffort: sessionModelReasoningEffort
};
messageQueue.push(formattedText, mode, localId);
if (localId) preparingLocalIds.add(localId);
userMessageChain = userMessageChain.then(async () => {
const wasCancelled = (): boolean => {
if (!localId) return false;
return cancelledBeforeEnqueue.delete(localId);
};
const buildMode = (): OpencodeMode => ({
permissionMode: currentPermissionMode,
// Propagate null distinctly from undefined so the launcher can
// tell "reset to default" (from `/model default`) apart from
// "model unchanged".
model: sessionModel,
modelReasoningEffort: sessionModelReasoningEffort
});
const pushPlain = () => {
const formattedText = formatMessageWithAttachments(message.content.text, message.content.attachments);
messageQueue.push(formattedText, buildMode(), localId);
};
try {
if (wasCancelled()) return;
let text = message.content.text;
const commands = await listSlashCommands('opencode', workingDirectory).catch(() => []);
if (wasCancelled()) return;
const slash = resolveOpencodeSlashCommand(text, {
commands,
permissionMode: currentPermissionMode,
model: sessionModel,
modelReasoningEffort: sessionModelReasoningEffort
});
if (slash.kind !== 'passthrough') {
if (slash.updates) {
if (slash.updates.permissionMode !== undefined) {
currentPermissionMode = slash.updates.permissionMode;
}
if (slash.updates.model !== undefined) {
sessionModel = slash.updates.model;
}
if (slash.updates.modelReasoningEffort !== undefined) {
sessionModelReasoningEffort = slash.updates.modelReasoningEffort;
}
syncSessionMode();
}
if (slash.kind === 'handled') {
// Ack the user's slash-command message before sending the
// agent reply. The web sorts the conversation by
// `invokedAt ?? createdAt` (web/src/lib/messages.ts), so
// stamping invokedAt first keeps the user prompt above
// the reply instead of below it. Pass
// `clearQueuedThinkingGrace` so the hub drops its 15s
// grace — this synchronous path never calls
// `onThinkingChange(true)`, so the next `thinking=false`
// keepalive must be honored immediately.
if (localId) {
session.emitMessagesConsumed([localId], { clearQueuedThinkingGrace: true });
}
if (slash.message) {
session.sendAgentMessage({
type: 'message',
message: slash.message,
id: randomUUID()
});
}
// Push a thinking=false keepalive immediately so the
// spinner clears without waiting for the next 2s tick.
// (The hub-side queued-thinking grace is dropped on
// messages-consumed above, so this keepalive is honored.)
sessionWrapperRef.current?.onThinkingChange(false);
return;
}
if (slash.message) {
session.sendAgentMessage({
type: 'message',
message: slash.message,
id: randomUUID()
});
}
text = slash.text;
}
const formattedText = formatMessageWithAttachments(text, message.content.attachments);
messageQueue.push(formattedText, buildMode(), localId);
} catch (error) {
logger.debug('[opencode] Failed to handle user message', error);
if (!wasCancelled()) {
pushPlain();
}
} finally {
if (localId) {
preparingLocalIds.delete(localId);
cancelledBeforeEnqueue.delete(localId);
}
}
}).catch((error) => {
logger.debug('[opencode] User message handler chain failed', error);
});
});
session.onCancelQueuedMessage((localId) => {
const removed = messageQueue.cancelByLocalId(localId);
logger.debug(`[opencode] cancelByLocalId(${localId}): ${removed ? 'removed' : 'not found (best-effort)'}`);
return removed;
const removedFromQueue = messageQueue.cancelByLocalId(localId);
if (removedFromQueue) {
logger.debug(`[opencode] cancelByLocalId(${localId}): removed from queue`);
return true;
}
if (preparingLocalIds.has(localId)) {
cancelledBeforeEnqueue.add(localId);
logger.debug(`[opencode] cancelByLocalId(${localId}): marked for cancellation before enqueue`);
return true;
}
logger.debug(`[opencode] cancelByLocalId(${localId}): not found (best-effort)`);
return false;
});
registerSessionConfigRpc<PermissionMode>({