feat: replace session commands with a natural-language stop
Remove the /compact, /clear and /stop session commands. They were gated to the main room or SESSION_COMMAND_ALLOWED_SENDERS, neither of which exists in this deployment, so nobody could use them. The agent-runner /compact passthrough goes with them. Instead, a short human message whose whole intent is "stop" (그만, 멈춰, 중단해, 하지 마, 취소, stop, cancel, ...; see src/stop-intent.ts) stops the room when it has something to stop: a running or queued run, an open paired task, or unprocessed human messages before it. The message loop then - advances the room cursors past the stop message (memory + router_state) - completes the open paired task as user_stopped, cancels its open turns and drops its execution lease - closes stdin with a user-stop reason and kills the agent through the existing GroupQueue.closeStdin/killProcess - replies "진행 중이던 작업을 중단했습니다." once When nothing is running the message is handled as a normal message. The user-stop close reason is treated like a human interruption, so the killed paired turn releases its lease without counting a failure and queues no follow-up, and the turn controller does not post the generic failure text on top of the stop reply. advanceLastAgentCursor no longer moves a cursor backwards, so a run that finishes after the stop cannot rewind the cursor and re-dispatch the stop message (the respawn seen when an agent was only killed). Stale SESSION_COMMAND_* keys in .env are now ignored instead of failing startup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -108,7 +108,7 @@ describe('filterProcessableMessages', () => {
|
||||
expect(result).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('filters session command control bot messages in paired rooms', () => {
|
||||
it('filters the stop confirmation bot message in paired rooms', () => {
|
||||
const isOwn = (m: NewMessage) =>
|
||||
m.is_bot_message === true && m.sender === OWN_BOT_ID;
|
||||
const result = filterProcessableMessages(
|
||||
@@ -118,8 +118,7 @@ describe('filterProcessableMessages', () => {
|
||||
id: 'control-1',
|
||||
sender: 'other-bot-456',
|
||||
sender_name: 'OtherBot',
|
||||
content:
|
||||
'Current session cleared. The next message will start a new conversation.',
|
||||
content: '진행 중이던 작업을 중단했습니다.',
|
||||
is_bot_message: true,
|
||||
}),
|
||||
makeMsg({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isSessionCommandControlMessage } from './session-commands.js';
|
||||
import { USER_STOP_REPLY } from './stop-intent.js';
|
||||
import { NewMessage } from './types.js';
|
||||
|
||||
const PAIRED_EXECUTION_CONTROL_MESSAGE_PATTERN =
|
||||
@@ -8,6 +8,10 @@ function isPairedExecutionControlMessage(content: string): boolean {
|
||||
return PAIRED_EXECUTION_CONTROL_MESSAGE_PATTERN.test(content.trim());
|
||||
}
|
||||
|
||||
function isUserStopReply(content: string): boolean {
|
||||
return content.trim() === USER_STOP_REPLY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter messages before processing.
|
||||
* - Normal rooms: drop all bot messages.
|
||||
@@ -23,7 +27,7 @@ export function filterProcessableMessages(
|
||||
(message) =>
|
||||
!(
|
||||
message.is_bot_message &&
|
||||
(isSessionCommandControlMessage(message.content) ||
|
||||
(isUserStopReply(message.content) ||
|
||||
isPairedExecutionControlMessage(message.content))
|
||||
),
|
||||
);
|
||||
|
||||
@@ -41,6 +41,7 @@ describe('config/env loading', () => {
|
||||
delete process.env.CODEX_WARMUP_FAILURE_COOLDOWN_MS;
|
||||
delete process.env.CODEX_WARMUP_MAX_CONSECUTIVE_FAILURES;
|
||||
delete process.env.SESSION_COMMAND_USER_IDS;
|
||||
delete process.env.SESSION_COMMAND_ALLOWED_SENDERS;
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
@@ -168,13 +169,12 @@ describe('config/env loading', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('fails fast when SESSION_COMMAND_USER_IDS is configured', async () => {
|
||||
it('ignores stale session command keys left in the environment', async () => {
|
||||
process.env.SESSION_COMMAND_USER_IDS = 'alice,bob';
|
||||
process.env.SESSION_COMMAND_ALLOWED_SENDERS = 'alice';
|
||||
|
||||
const { loadConfig } = await import('./config/load-config.js');
|
||||
|
||||
expect(() => loadConfig()).toThrow(
|
||||
/Legacy env aliases are no longer supported; remove or rename \(SESSION_COMMAND_USER_IDS\) to the canonical keys/,
|
||||
);
|
||||
expect(() => loadConfig()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -142,9 +142,3 @@ export const CODEX_WARMUP_CONFIG = CONFIG.codexWarmup;
|
||||
// Timezone for scheduled tasks (cron expressions, etc.)
|
||||
// Uses system timezone by default
|
||||
export const TIMEZONE = CONFIG.status.timezone;
|
||||
|
||||
const SESSION_COMMAND_ALLOWED_SENDERS = CONFIG.sessionCommands.allowedSenders;
|
||||
|
||||
export function isSessionCommandSenderAllowed(sender: string): boolean {
|
||||
return SESSION_COMMAND_ALLOWED_SENDERS.has(sender);
|
||||
}
|
||||
|
||||
@@ -12,10 +12,6 @@ const CANONICAL_DISCORD_CHANNEL_TOKEN_KEYS = new Set([
|
||||
'DISCORD_ARBITER_BOT_TOKEN',
|
||||
]);
|
||||
|
||||
const CANONICAL_SESSION_COMMAND_KEYS = new Set([
|
||||
'SESSION_COMMAND_ALLOWED_SENDERS',
|
||||
]);
|
||||
|
||||
function readText(key: string): string | undefined {
|
||||
return getEnv(key);
|
||||
}
|
||||
@@ -90,9 +86,6 @@ function assertNoLegacyEnvAliasesConfigured(): void {
|
||||
if (key.startsWith('DISCORD_') && key.endsWith('_BOT_TOKEN')) {
|
||||
return !CANONICAL_DISCORD_CHANNEL_TOKEN_KEYS.has(key);
|
||||
}
|
||||
if (key.startsWith('SESSION_COMMAND_')) {
|
||||
return !CANONICAL_SESSION_COMMAND_KEYS.has(key);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
@@ -101,7 +94,7 @@ function assertNoLegacyEnvAliasesConfigured(): void {
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Legacy env aliases are no longer supported; remove or rename (${configuredAliases.join(', ')}) to the canonical keys DISCORD_OWNER_BOT_TOKEN, DISCORD_REVIEWER_BOT_TOKEN, DISCORD_ARBITER_BOT_TOKEN, SESSION_COMMAND_ALLOWED_SENDERS`,
|
||||
`Legacy env aliases are no longer supported; remove or rename (${configuredAliases.join(', ')}) to the canonical keys DISCORD_OWNER_BOT_TOKEN, DISCORD_REVIEWER_BOT_TOKEN, DISCORD_ARBITER_BOT_TOKEN`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -270,13 +263,5 @@ export function loadConfig(): AppConfig {
|
||||
1,
|
||||
),
|
||||
},
|
||||
sessionCommands: {
|
||||
allowedSenders: new Set(
|
||||
(readText('SESSION_COMMAND_ALLOWED_SENDERS') ?? '')
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,7 +88,4 @@ export interface AppConfig {
|
||||
failureCooldownMs: number;
|
||||
maxConsecutiveFailures: number;
|
||||
};
|
||||
sessionCommands: {
|
||||
allowedSenders: Set<string>;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -105,6 +105,7 @@ export {
|
||||
refreshPairedTaskExecutionLease,
|
||||
recoverInterruptedPairedTurnAttemptsForService,
|
||||
releasePairedTaskExecutionLease,
|
||||
releasePairedTaskExecutionLeasesForTask,
|
||||
reservePairedTurnReservation,
|
||||
setChannelOwnerLease,
|
||||
updatePairedTask,
|
||||
|
||||
@@ -823,6 +823,16 @@ export function releasePairedTaskExecutionLeaseInDatabase(
|
||||
.run(args.taskId, CURRENT_SERVICE_ID, args.runId);
|
||||
}
|
||||
|
||||
/** Drop every execution lease held on a task, regardless of the claiming run. */
|
||||
export function releasePairedTaskExecutionLeasesForTaskInDatabase(
|
||||
database: Database,
|
||||
taskId: string,
|
||||
): number {
|
||||
return database
|
||||
.prepare('DELETE FROM paired_task_execution_leases WHERE task_id = ?')
|
||||
.run(taskId).changes;
|
||||
}
|
||||
|
||||
export function refreshPairedTaskExecutionLeaseInDatabase(
|
||||
database: Database,
|
||||
args: {
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
listPairedWorkspacesForTaskFromDatabase,
|
||||
refreshPairedTaskExecutionLeaseInDatabase,
|
||||
releasePairedTaskExecutionLeaseInDatabase,
|
||||
releasePairedTaskExecutionLeasesForTaskInDatabase,
|
||||
reservePairedTurnReservationInDatabase,
|
||||
updatePairedTaskIfUnchangedInDatabase,
|
||||
updatePairedTaskInDatabase,
|
||||
@@ -172,6 +173,15 @@ export function releasePairedTaskExecutionLease(args: {
|
||||
releasePairedTaskExecutionLeaseInDatabase(requireDatabase(), args);
|
||||
}
|
||||
|
||||
export function releasePairedTaskExecutionLeasesForTask(
|
||||
taskId: string,
|
||||
): number {
|
||||
return releasePairedTaskExecutionLeasesForTaskInDatabase(
|
||||
requireDatabase(),
|
||||
taskId,
|
||||
);
|
||||
}
|
||||
|
||||
export function refreshPairedTaskExecutionLease(args: {
|
||||
taskId: string;
|
||||
runId: string;
|
||||
|
||||
@@ -511,7 +511,7 @@ export class GroupQueue {
|
||||
runId: state.currentRunId,
|
||||
processName: state.processName,
|
||||
},
|
||||
'Killing agent process via /stop command',
|
||||
'Killing agent process on user stop request',
|
||||
);
|
||||
try {
|
||||
// SIGTERM allows the runner to call AbortController.abort() for graceful cleanup.
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
STATUS_CHANNEL_ID,
|
||||
STATUS_UPDATE_INTERVAL,
|
||||
TIMEZONE,
|
||||
TRIGGER_PATTERN,
|
||||
USAGE_UPDATE_INTERVAL,
|
||||
} from './config.js';
|
||||
import './channels/index.js';
|
||||
@@ -125,7 +124,6 @@ const runtime = createMessageRuntime({
|
||||
idleTimeout: IDLE_TIMEOUT,
|
||||
pollInterval: POLL_INTERVAL,
|
||||
timezone: TIMEZONE,
|
||||
triggerPattern: TRIGGER_PATTERN,
|
||||
channels,
|
||||
queue,
|
||||
getRoomBindings: runtimeState.getRoomBindings,
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
export const HUMAN_MESSAGE_DETECTED_CLOSE_REASON = 'human-message-detected';
|
||||
export const USER_STOP_CLOSE_REASON = 'user-stop';
|
||||
|
||||
/**
|
||||
* True when a human interrupted the run, either with a new message or with an
|
||||
* explicit stop request. Interrupted runs release their paired lease without
|
||||
* counting a failure and do not queue follow-ups.
|
||||
*/
|
||||
export function isHumanMessageCloseReason(
|
||||
reason: string | null | undefined,
|
||||
): boolean {
|
||||
return reason === HUMAN_MESSAGE_DETECTED_CLOSE_REASON;
|
||||
return (
|
||||
reason === HUMAN_MESSAGE_DETECTED_CLOSE_REASON ||
|
||||
reason === USER_STOP_CLOSE_REASON
|
||||
);
|
||||
}
|
||||
|
||||
/** True when the run was killed because a human asked the room to stop. */
|
||||
export function isUserStopCloseReason(
|
||||
reason: string | null | undefined,
|
||||
): boolean {
|
||||
return reason === USER_STOP_CLOSE_REASON;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ function defaultArgs(
|
||||
channel,
|
||||
assistantName: '오너',
|
||||
failureFinalText: 'FAILED',
|
||||
triggerPattern: /^\/clear\b/,
|
||||
hasImplicitContinuationWindow: vi.fn(() => false),
|
||||
lastAgentTimestamps: {},
|
||||
saveState: vi.fn(),
|
||||
@@ -81,6 +80,11 @@ function defaultArgs(
|
||||
sendQueuedMessage: vi.fn(() => true),
|
||||
closeStdin: vi.fn(),
|
||||
isRunningMessageTurn: vi.fn(() => true),
|
||||
roomStopControls: {
|
||||
hasQueuedWork: vi.fn(() => true),
|
||||
stopRunningAgent: vi.fn(() => true),
|
||||
sendReply: vi.fn(async () => {}),
|
||||
},
|
||||
labelPairedSenders: vi.fn((_jid, messages) => messages),
|
||||
formatMessages: vi.fn((messages: NewMessage[]) =>
|
||||
messages.map((item) => item.content).join('\n'),
|
||||
|
||||
@@ -14,11 +14,7 @@ import {
|
||||
shouldSkipBotOnlyCollaboration,
|
||||
} from './message-runtime-rules.js';
|
||||
import { enqueuePairedFollowUpAfterEvent } from './message-runtime-follow-up.js';
|
||||
import {
|
||||
extractSessionCommand,
|
||||
isSessionCommandAllowed,
|
||||
} from './session-commands.js';
|
||||
import { isSessionCommandSenderAllowed } from './config.js';
|
||||
import { stopRoomWorkIfRequested, type RoomStopControls } from './room-stop.js';
|
||||
import { hasReviewerLease } from './service-routing.js';
|
||||
import type { ExecuteTurnFn } from './message-runtime-types.js';
|
||||
import type { ScheduledPairedFollowUpIntentKind } from './paired-follow-up-scheduler.js';
|
||||
@@ -224,7 +220,6 @@ export async function processLoopGroupMessages(args: {
|
||||
channel: Channel;
|
||||
assistantName: string;
|
||||
failureFinalText: string;
|
||||
triggerPattern: RegExp;
|
||||
hasImplicitContinuationWindow: (
|
||||
chatJid: string,
|
||||
messages: NewMessage[],
|
||||
@@ -242,11 +237,11 @@ export async function processLoopGroupMessages(args: {
|
||||
sendQueuedMessage: (chatJid: string, text: string) => boolean;
|
||||
closeStdin: (reason: string) => void;
|
||||
isRunningMessageTurn: (chatJid: string) => boolean;
|
||||
roomStopControls: RoomStopControls;
|
||||
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
|
||||
formatMessages: (messages: NewMessage[], timezone: string) => string;
|
||||
}): Promise<void> {
|
||||
const { chatJid, group, groupMessages, channel } = args;
|
||||
const isMainGroup = group.isMain === true;
|
||||
const processableGroupMessages = getProcessableMessages(
|
||||
chatJid,
|
||||
groupMessages,
|
||||
@@ -284,21 +279,20 @@ export async function processLoopGroupMessages(args: {
|
||||
return;
|
||||
}
|
||||
|
||||
const loopCmdMsg = groupMessages.find(
|
||||
(msg) => extractSessionCommand(msg.content, args.triggerPattern) !== null,
|
||||
);
|
||||
|
||||
if (loopCmdMsg) {
|
||||
if (
|
||||
isSessionCommandAllowed(
|
||||
isMainGroup,
|
||||
loopCmdMsg.is_from_me === true,
|
||||
isSessionCommandSenderAllowed(loopCmdMsg.sender),
|
||||
)
|
||||
) {
|
||||
args.closeStdin('session-command-detected');
|
||||
const stopResult = await stopRoomWorkIfRequested({
|
||||
chatJid,
|
||||
group,
|
||||
channel,
|
||||
messages: processableGroupMessages,
|
||||
assistantName: args.assistantName,
|
||||
lastAgentTimestamps: args.lastAgentTimestamps,
|
||||
saveState: args.saveState,
|
||||
controls: args.roomStopControls,
|
||||
});
|
||||
if (stopResult.stopped) {
|
||||
if (stopResult.hasMessagesAfterStop) {
|
||||
args.enqueueMessageCheck();
|
||||
}
|
||||
args.enqueueMessageCheck();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { RegisteredGroup } from './types.js';
|
||||
|
||||
const { handleSessionCommandMock } = vi.hoisted(() => ({
|
||||
handleSessionCommandMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./session-commands.js', () => ({
|
||||
handleSessionCommand: handleSessionCommandMock,
|
||||
}));
|
||||
|
||||
import { handleQueuedRunGates } from './message-runtime-gating.js';
|
||||
|
||||
function makeArgs(overrides: {
|
||||
chatJid?: string;
|
||||
sendMessage?: () => Promise<void>;
|
||||
}) {
|
||||
return {
|
||||
chatJid: overrides.chatJid ?? 'room-1',
|
||||
group: {
|
||||
folder: 'room-folder',
|
||||
name: 'room',
|
||||
isMain: false,
|
||||
trigger: '코덱스',
|
||||
added_at: new Date().toISOString(),
|
||||
} satisfies RegisteredGroup,
|
||||
runId: 'run-1',
|
||||
missedMessages: [],
|
||||
triggerPattern: /^코덱스/,
|
||||
timezone: 'Asia/Seoul',
|
||||
hasImplicitContinuationWindow: () => false,
|
||||
sessionCommandDeps: {
|
||||
sendMessage: overrides.sendMessage ?? (async () => {}),
|
||||
} as never,
|
||||
};
|
||||
}
|
||||
|
||||
describe('message-runtime-gating', () => {
|
||||
beforeEach(() => {
|
||||
handleSessionCommandMock.mockReset();
|
||||
});
|
||||
|
||||
it('returns session-command results directly when a command is handled', async () => {
|
||||
handleSessionCommandMock.mockResolvedValue({
|
||||
handled: true,
|
||||
success: false,
|
||||
});
|
||||
|
||||
const result = await handleQueuedRunGates(makeArgs({}));
|
||||
|
||||
expect(result).toEqual({ handled: true, success: false });
|
||||
});
|
||||
|
||||
it('falls through when no session command matched', async () => {
|
||||
handleSessionCommandMock.mockResolvedValue({ handled: false });
|
||||
|
||||
const result = await handleQueuedRunGates(makeArgs({}));
|
||||
|
||||
expect(result).toEqual({ handled: false });
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import {
|
||||
handleSessionCommand,
|
||||
type SessionCommandDeps,
|
||||
} from './session-commands.js';
|
||||
import type { NewMessage, RegisteredGroup } from './types.js';
|
||||
|
||||
export async function handleQueuedRunGates(args: {
|
||||
chatJid: string;
|
||||
group: RegisteredGroup;
|
||||
runId: string;
|
||||
missedMessages: NewMessage[];
|
||||
triggerPattern: RegExp;
|
||||
timezone: string;
|
||||
hasImplicitContinuationWindow: (
|
||||
chatJid: string,
|
||||
messages: NewMessage[],
|
||||
) => boolean;
|
||||
sessionCommandDeps: SessionCommandDeps;
|
||||
}): Promise<{ handled: true; success: boolean } | { handled: false }> {
|
||||
const cmdResult = await handleSessionCommand({
|
||||
missedMessages: args.missedMessages,
|
||||
isMainGroup: args.group.isMain === true,
|
||||
groupName: args.group.name,
|
||||
runId: args.runId,
|
||||
triggerPattern: args.triggerPattern,
|
||||
timezone: args.timezone,
|
||||
deps: args.sessionCommandDeps,
|
||||
});
|
||||
if (cmdResult.handled) {
|
||||
return cmdResult;
|
||||
}
|
||||
|
||||
return { handled: false };
|
||||
}
|
||||
@@ -5,14 +5,10 @@ import {
|
||||
markWorkItemDelivered,
|
||||
type WorkItem,
|
||||
} from './db.js';
|
||||
import {
|
||||
isSessionCommandSenderAllowed,
|
||||
SERVICE_SESSION_SCOPE,
|
||||
} from './config.js';
|
||||
import { SERVICE_SESSION_SCOPE } from './config.js';
|
||||
import { resolveRuntimeAttachmentBaseDirs } from './attachment-base-dirs.js';
|
||||
import { enqueueGenericFollowUpAfterDeliveryRetry as enqueueDeliveryRetryFollowUp } from './message-runtime-dispatch.js';
|
||||
import { processOpenWorkItemDelivery } from './message-runtime-delivery.js';
|
||||
import { handleQueuedRunGates } from './message-runtime-gating.js';
|
||||
import {
|
||||
runPendingPairedTurnIfNeeded,
|
||||
runQueuedGroupTurn,
|
||||
@@ -24,7 +20,6 @@ import {
|
||||
shouldSkipBotOnlyCollaboration,
|
||||
} from './message-runtime-rules.js';
|
||||
import { resolveOwnerTaskForHumanMessage } from './paired-execution-context.js';
|
||||
import { transitionPairedTaskStatus } from './paired-task-status.js';
|
||||
import { hasReviewerLease } from './service-routing.js';
|
||||
import {
|
||||
getFixedRoleChannelName,
|
||||
@@ -41,8 +36,8 @@ import {
|
||||
RELOGIN_REQUIRED_MESSAGE,
|
||||
} from './token-refresh.js';
|
||||
import { findChannel, formatMessages } from './router.js';
|
||||
import { stopRoomWorkIfRequested, type RoomStopResult } from './room-stop.js';
|
||||
import { createScopedLogger, logger } from './logger.js';
|
||||
import type { AgentOutput } from './agent-runner.js';
|
||||
import type { GroupQueue, GroupRunContext } from './group-queue.js';
|
||||
import type {
|
||||
ExecuteTurnFn,
|
||||
@@ -55,31 +50,16 @@ import type {
|
||||
RegisteredGroup,
|
||||
} from './types.js';
|
||||
|
||||
type RunAgentFn = (
|
||||
group: RegisteredGroup,
|
||||
prompt: string,
|
||||
chatJid: string,
|
||||
runId: string,
|
||||
onOutput?: (output: AgentOutput) => Promise<void>,
|
||||
) => Promise<'success' | 'error'>;
|
||||
|
||||
interface ProcessGroupMessagesDeps {
|
||||
assistantName: string;
|
||||
failureFinalText: string;
|
||||
timezone: string;
|
||||
triggerPattern: RegExp;
|
||||
channels: Channel[];
|
||||
queue: Pick<GroupQueue, 'enqueueMessageCheck' | 'closeStdin' | 'killProcess'>;
|
||||
queue: Pick<GroupQueue, 'enqueueMessageCheck'>;
|
||||
getRoomBindings: () => Record<string, RegisteredGroup>;
|
||||
getLastAgentTimestamps: () => Record<string, string>;
|
||||
saveState: () => void;
|
||||
clearSession: (groupFolder: string, opts?: { allRoles?: boolean }) => void;
|
||||
runAgent: RunAgentFn;
|
||||
executeTurn: ExecuteTurnFn;
|
||||
hasImplicitContinuationWindow: (
|
||||
chatJid: string,
|
||||
messages: NewMessage[],
|
||||
) => boolean;
|
||||
openContinuation: (chatJid: string) => void;
|
||||
isDuplicateOfLastBotFinal: (chatJid: string, text: string) => boolean;
|
||||
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
|
||||
@@ -307,9 +287,10 @@ async function processMissedMessages(
|
||||
return true;
|
||||
}
|
||||
|
||||
const gateOutcome = await runQueuedRunGates(args, runtime, missedMessages);
|
||||
if (gateOutcome !== null) {
|
||||
return gateOutcome;
|
||||
const stopResult = await runStopRequestGate(args, runtime, missedMessages);
|
||||
if (stopResult.stopped) {
|
||||
if (stopResult.hasMessagesAfterStop) continue;
|
||||
return true;
|
||||
}
|
||||
|
||||
const reloginOutcome = await runReloginRequiredGate(
|
||||
@@ -449,11 +430,7 @@ async function runReloginRequiredGate(
|
||||
if (agentType !== 'claude-code') return null;
|
||||
if (!isReloginRequired()) return null;
|
||||
|
||||
await deliverSessionCommandMessage(
|
||||
args,
|
||||
runtime.chatJid,
|
||||
RELOGIN_REQUIRED_MESSAGE,
|
||||
);
|
||||
await deliverRoomNotice(args, runtime.chatJid, RELOGIN_REQUIRED_MESSAGE);
|
||||
|
||||
const lastMessage = missedMessages[missedMessages.length - 1];
|
||||
if (lastMessage?.seq != null) {
|
||||
@@ -470,75 +447,34 @@ async function runReloginRequiredGate(
|
||||
return true;
|
||||
}
|
||||
|
||||
async function runQueuedRunGates(
|
||||
/**
|
||||
* A stop request that reaches a queued run without having been handled by the
|
||||
* message loop (e.g. it was pending across a restart) still stops the room's
|
||||
* open paired task instead of being sent to the agent as a prompt.
|
||||
*/
|
||||
async function runStopRequestGate(
|
||||
args: ProcessGroupMessagesDeps,
|
||||
runtime: RuntimeContext,
|
||||
missedMessages: NewMessage[],
|
||||
): Promise<boolean | null> {
|
||||
const gateResult = await handleQueuedRunGates({
|
||||
): Promise<RoomStopResult> {
|
||||
return stopRoomWorkIfRequested({
|
||||
chatJid: runtime.chatJid,
|
||||
group: runtime.group,
|
||||
runId: runtime.runId,
|
||||
missedMessages,
|
||||
triggerPattern: args.triggerPattern,
|
||||
timezone: args.timezone,
|
||||
hasImplicitContinuationWindow: args.hasImplicitContinuationWindow,
|
||||
sessionCommandDeps: {
|
||||
sendMessage: (text) =>
|
||||
deliverSessionCommandMessage(args, runtime.chatJid, text),
|
||||
setTyping: (typing) =>
|
||||
runtime.channel.setTyping?.(runtime.chatJid, typing) ??
|
||||
Promise.resolve(),
|
||||
runAgent: (prompt, onOutput) =>
|
||||
args.runAgent(
|
||||
runtime.group,
|
||||
prompt,
|
||||
runtime.chatJid,
|
||||
runtime.runId,
|
||||
onOutput,
|
||||
),
|
||||
closeStdin: () =>
|
||||
args.queue.closeStdin(runtime.chatJid, {
|
||||
reason: 'session-command',
|
||||
}),
|
||||
clearSession: (opts) => args.clearSession(runtime.group.folder, opts),
|
||||
advanceCursor: (cursorOrTimestamp) => {
|
||||
advanceLastAgentCursor(
|
||||
args.getLastAgentTimestamps(),
|
||||
args.saveState,
|
||||
runtime.chatJid,
|
||||
cursorOrTimestamp,
|
||||
);
|
||||
},
|
||||
formatMessages,
|
||||
isAdminSender: (msg) => isSessionCommandSenderAllowed(msg.sender),
|
||||
canSenderInteract: () => true,
|
||||
resetPairedTask: () => completePairedTaskAsStopped(runtime.chatJid),
|
||||
killProcess: () => args.queue.killProcess(runtime.chatJid),
|
||||
},
|
||||
});
|
||||
return gateResult.handled ? gateResult.success : null;
|
||||
}
|
||||
|
||||
function completePairedTaskAsStopped(chatJid: string): void {
|
||||
if (!hasReviewerLease(chatJid)) return;
|
||||
const task = getLatestOpenPairedTaskForChat(chatJid);
|
||||
if (!task) return;
|
||||
|
||||
const now = new Date().toISOString();
|
||||
transitionPairedTaskStatus({
|
||||
taskId: task.id,
|
||||
currentStatus: task.status,
|
||||
nextStatus: 'completed',
|
||||
expectedUpdatedAt: task.updated_at,
|
||||
updatedAt: now,
|
||||
patch: {
|
||||
completion_reason: 'stopped',
|
||||
channel: runtime.channel,
|
||||
messages: missedMessages,
|
||||
assistantName: args.assistantName,
|
||||
lastAgentTimestamps: args.getLastAgentTimestamps(),
|
||||
saveState: args.saveState,
|
||||
controls: {
|
||||
// This run is the room's queued work; it has not started an agent yet.
|
||||
hasQueuedWork: () => false,
|
||||
stopRunningAgent: () => false,
|
||||
sendReply: (chatJid, text) => deliverRoomNotice(args, chatJid, text),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function deliverSessionCommandMessage(
|
||||
export async function deliverRoomNotice(
|
||||
deps: Pick<ProcessGroupMessagesDeps, 'channels' | 'getRoomBindings'>,
|
||||
chatJid: string,
|
||||
text: string,
|
||||
|
||||
@@ -13,13 +13,13 @@ import {
|
||||
import { SERVICE_SESSION_SCOPE } from './config.js';
|
||||
import type { schedulePairedFollowUpWithMessageCheck } from './message-runtime-follow-up.js';
|
||||
import type { ExecuteTurnFn } from './message-runtime-types.js';
|
||||
import type { RoomStopControls } from './room-stop.js';
|
||||
import { findChannel, formatMessages } from './router.js';
|
||||
import type { Channel, NewMessage, RegisteredGroup } from './types.js';
|
||||
|
||||
export async function processMessageLoopTick(args: {
|
||||
assistantName: string;
|
||||
failureFinalText: string;
|
||||
triggerPattern: RegExp;
|
||||
timezone: string;
|
||||
channels: Channel[];
|
||||
getRoomBindings: () => Record<string, RegisteredGroup>;
|
||||
@@ -41,6 +41,7 @@ export async function processMessageLoopTick(args: {
|
||||
sendQueuedMessage: (chatJid: string, text: string) => boolean;
|
||||
closeStdin: (chatJid: string, reason: string) => void;
|
||||
isRunningMessageTurn: (chatJid: string) => boolean;
|
||||
roomStopControls: RoomStopControls;
|
||||
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
|
||||
}): Promise<void> {
|
||||
args.enqueuePendingHandoffs();
|
||||
@@ -87,7 +88,6 @@ export async function processMessageLoopTick(args: {
|
||||
channel,
|
||||
assistantName: args.assistantName,
|
||||
failureFinalText: args.failureFinalText,
|
||||
triggerPattern: args.triggerPattern,
|
||||
hasImplicitContinuationWindow: args.hasImplicitContinuationWindow,
|
||||
lastAgentTimestamps: args.lastAgentTimestamps,
|
||||
saveState: args.saveState,
|
||||
@@ -107,6 +107,7 @@ export async function processMessageLoopTick(args: {
|
||||
sendQueuedMessage: args.sendQueuedMessage,
|
||||
closeStdin: (reason) => args.closeStdin(chatJid, reason),
|
||||
isRunningMessageTurn: args.isRunningMessageTurn,
|
||||
roomStopControls: args.roomStopControls,
|
||||
labelPairedSenders: args.labelPairedSenders,
|
||||
formatMessages,
|
||||
});
|
||||
|
||||
@@ -99,7 +99,6 @@ describe('message-runtime progress entry path', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
|
||||
@@ -62,14 +62,18 @@ export function advanceLastAgentCursor(
|
||||
cursorKey?: string,
|
||||
): void {
|
||||
const key = cursorKey ?? chatJid;
|
||||
if (typeof cursorOrTimestamp === 'number') {
|
||||
lastAgentTimestamps[key] = String(cursorOrTimestamp);
|
||||
} else {
|
||||
lastAgentTimestamps[key] = normalizeStoredSeqCursor(
|
||||
cursorOrTimestamp,
|
||||
chatJid,
|
||||
);
|
||||
const next =
|
||||
typeof cursorOrTimestamp === 'number'
|
||||
? String(cursorOrTimestamp)
|
||||
: normalizeStoredSeqCursor(cursorOrTimestamp, chatJid);
|
||||
// Cursors only move forward. A run that finishes after a newer message was
|
||||
// already consumed (e.g. a user stop request) must not rewind the cursor and
|
||||
// re-dispatch that message.
|
||||
const current = lastAgentTimestamps[key];
|
||||
if (current !== undefined && Number(next) < Number(current)) {
|
||||
return;
|
||||
}
|
||||
lastAgentTimestamps[key] = next;
|
||||
saveState();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ vi.mock('./config.js', () => ({
|
||||
normalizeServiceId: vi.fn((serviceId: string) => serviceId),
|
||||
isClaudeService: vi.fn(() => true),
|
||||
isReviewService: vi.fn(() => false),
|
||||
isSessionCommandSenderAllowed: vi.fn(() => false),
|
||||
TIMEZONE: 'Asia/Seoul',
|
||||
}));
|
||||
|
||||
@@ -270,13 +269,6 @@ vi.mock('./sender-allowlist.js', () => ({
|
||||
loadSenderAllowlist: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock('./session-commands.js', () => ({
|
||||
extractSessionCommand: vi.fn(() => null),
|
||||
handleSessionCommand: vi.fn(async () => ({ handled: false })),
|
||||
isSessionCommandAllowed: vi.fn(() => true),
|
||||
isSessionCommandControlMessage: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
import * as agentRunner from './agent-runner.js';
|
||||
import * as db from './db.js';
|
||||
import { resolveGroupIpcPath } from './group-folder.js';
|
||||
@@ -359,7 +351,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
@@ -429,7 +420,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
@@ -507,7 +497,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -559,7 +548,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -627,7 +615,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -753,7 +740,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -865,7 +851,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -949,7 +934,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1039,7 +1023,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1122,7 +1105,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1216,7 +1198,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1337,7 +1318,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1430,7 +1410,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1526,7 +1505,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1603,7 +1581,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1723,7 +1700,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -1830,7 +1806,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2203,7 +2178,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2322,7 +2296,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2431,7 +2404,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2559,7 +2531,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2659,7 +2630,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2755,7 +2725,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2848,7 +2817,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -2943,7 +2911,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel, arbiterChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3056,7 +3023,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel, arbiterChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3172,7 +3138,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3264,7 +3229,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3353,7 +3317,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3417,7 +3380,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel],
|
||||
queue: {
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
@@ -3491,7 +3453,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3561,7 +3522,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3679,7 +3639,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'Asia/Seoul',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, reviewerChannel],
|
||||
queue: {
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
@@ -3795,7 +3754,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'Asia/Seoul',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [ownerChannel, arbiterChannel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3873,7 +3831,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 60_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -3957,7 +3914,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4049,7 +4005,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4140,7 +4095,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4241,7 +4195,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4322,7 +4275,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4424,7 +4376,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 20_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4541,7 +4492,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4647,7 +4597,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4725,7 +4674,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4786,7 +4734,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4874,7 +4821,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -4949,7 +4895,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5055,7 +5000,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5181,7 +5125,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5297,7 +5240,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5378,7 +5320,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 60_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5454,7 +5395,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5537,7 +5477,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5610,7 +5549,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [channel],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5668,7 +5606,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [makeChannel(chatJid)],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
@@ -5728,7 +5665,6 @@ describe('createMessageRuntime', () => {
|
||||
idleTimeout: 1_000,
|
||||
pollInterval: 1_000,
|
||||
timezone: 'UTC',
|
||||
triggerPattern: /^@Andy\b/i,
|
||||
channels: [makeChannel(chatJid)],
|
||||
queue: {
|
||||
registerProcess: vi.fn(),
|
||||
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
} from './message-runtime-turns.js';
|
||||
import { handleMessageRuntimeAfterDeliverySuccess } from './message-runtime-after-delivery.js';
|
||||
import { deliverMessageRuntimeFinalText } from './message-runtime-final-delivery.js';
|
||||
import { createProcessGroupMessages } from './message-runtime-group-processing.js';
|
||||
import {
|
||||
createProcessGroupMessages,
|
||||
deliverRoomNotice,
|
||||
} from './message-runtime-group-processing.js';
|
||||
import { USER_STOP_CLOSE_REASON } from './message-close-reasons.js';
|
||||
import type { RoomStopControls } from './room-stop.js';
|
||||
|
||||
export { isDuplicateOfLastBotFinal };
|
||||
|
||||
@@ -27,7 +32,6 @@ export interface MessageRuntimeDeps {
|
||||
idleTimeout: number;
|
||||
pollInterval: number;
|
||||
timezone: string;
|
||||
triggerPattern: RegExp;
|
||||
channels: Channel[];
|
||||
queue: GroupQueue;
|
||||
getRoomBindings: () => Record<string, RegisteredGroup>;
|
||||
@@ -66,6 +70,26 @@ function createStartMessageLoop(args: {
|
||||
};
|
||||
}
|
||||
|
||||
function createRoomStopControls(
|
||||
deps: Pick<MessageRuntimeDeps, 'queue' | 'channels' | 'getRoomBindings'>,
|
||||
): RoomStopControls {
|
||||
return {
|
||||
hasQueuedWork: (chatJid) =>
|
||||
(deps.queue.getStatuses([chatJid])[0]?.status ?? 'inactive') !==
|
||||
'inactive',
|
||||
stopRunningAgent: (chatJid) => {
|
||||
deps.queue.closeStdin(chatJid, { reason: USER_STOP_CLOSE_REASON });
|
||||
return deps.queue.killProcess(chatJid);
|
||||
},
|
||||
sendReply: (chatJid, text) =>
|
||||
deliverRoomNotice(
|
||||
{ channels: deps.channels, getRoomBindings: deps.getRoomBindings },
|
||||
chatJid,
|
||||
text,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
||||
processGroupMessages: (
|
||||
chatJid: string,
|
||||
@@ -181,28 +205,25 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
||||
assistantName: deps.assistantName,
|
||||
failureFinalText: FAILURE_FINAL_TEXT,
|
||||
timezone: deps.timezone,
|
||||
triggerPattern: deps.triggerPattern,
|
||||
channels: deps.channels,
|
||||
queue: deps.queue,
|
||||
getRoomBindings: deps.getRoomBindings,
|
||||
getLastAgentTimestamps: deps.getLastAgentTimestamps,
|
||||
saveState: deps.saveState,
|
||||
clearSession: deps.clearSession,
|
||||
runAgent,
|
||||
executeTurn,
|
||||
hasImplicitContinuationWindow: continuationTracker.has,
|
||||
openContinuation: continuationTracker.open,
|
||||
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
||||
labelPairedSenders: labelPairedRuntimeSenders,
|
||||
});
|
||||
|
||||
const roomStopControls = createRoomStopControls(deps);
|
||||
|
||||
const startMessageLoop = createStartMessageLoop({
|
||||
pollInterval: deps.pollInterval,
|
||||
processTick: async () => {
|
||||
await processMessageLoopTick({
|
||||
assistantName: deps.assistantName,
|
||||
failureFinalText: FAILURE_FINAL_TEXT,
|
||||
triggerPattern: deps.triggerPattern,
|
||||
timezone: deps.timezone,
|
||||
channels: deps.channels,
|
||||
getRoomBindings: deps.getRoomBindings,
|
||||
@@ -222,6 +243,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
||||
}),
|
||||
isRunningMessageTurn: (chatJid) =>
|
||||
deps.queue.getStatuses([chatJid])[0]?.runPhase === 'running_messages',
|
||||
roomStopControls,
|
||||
labelPairedSenders: labelPairedRuntimeSenders,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -992,4 +992,28 @@ describe('MessageTurnController human interruptions', () => {
|
||||
expect(channel.sendAndTrack).toHaveBeenCalledTimes(1);
|
||||
expect(deliverFinalText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not publish a failure final when the user stopped the run', async () => {
|
||||
const channel = { ...makeChannel(), name: 'discord' } satisfies Channel;
|
||||
const deliverFinalText = vi.fn().mockResolvedValue(true);
|
||||
const controller = new MessageTurnController({
|
||||
chatJid: 'dc:test-room',
|
||||
group: makeGroup(),
|
||||
runId: 'run-user-stopped',
|
||||
channel,
|
||||
idleTimeout: 1_000,
|
||||
failureFinalText: '실패',
|
||||
isClaudeCodeAgent: true,
|
||||
clearSession: vi.fn(),
|
||||
requestClose: vi.fn(),
|
||||
deliverFinalText,
|
||||
deliveryRole: 'owner',
|
||||
getCloseReason: () => 'user-stop',
|
||||
});
|
||||
|
||||
await controller.start();
|
||||
await controller.finish('error');
|
||||
|
||||
expect(deliverFinalText).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,10 @@ import { shouldResetSessionOnAgentFailure } from './session-recovery.js';
|
||||
import { TASK_STATUS_MESSAGE_PREFIX } from './task-watch-status.js';
|
||||
import { formatElapsedKorean } from './utils.js';
|
||||
import type { PairedTurnIdentity } from './paired-turn-identity.js';
|
||||
import { isHumanMessageCloseReason } from './message-close-reasons.js';
|
||||
import {
|
||||
isHumanMessageCloseReason,
|
||||
isUserStopCloseReason,
|
||||
} from './message-close-reasons.js';
|
||||
import {
|
||||
normalizeAgentOutputPhase,
|
||||
toVisiblePhase,
|
||||
@@ -872,6 +875,12 @@ export class MessageTurnController {
|
||||
if (this.terminalObserved()) {
|
||||
return;
|
||||
}
|
||||
if (isUserStopCloseReason(this.options.getCloseReason?.() ?? null)) {
|
||||
// The user asked the room to stop and already got a stop reply; the
|
||||
// killed run must not add a "failed" message on top of it.
|
||||
this.log.info('Skipped failure final because the user stopped the run');
|
||||
return;
|
||||
}
|
||||
await this.publishTerminalText(
|
||||
appendErrorDetailToFailureText(
|
||||
this.options.failureFinalText,
|
||||
|
||||
328
src/room-stop.test.ts
Normal file
328
src/room-stop.test.ts
Normal file
@@ -0,0 +1,328 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('./service-routing.js', () => ({
|
||||
hasReviewerLease: vi.fn(() => false),
|
||||
resolveLeaseServiceId: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
import {
|
||||
_initTestDatabase,
|
||||
claimPairedTurnReservation,
|
||||
createPairedTask,
|
||||
getMessagesSinceSeq,
|
||||
getPairedTaskById,
|
||||
getPairedTurnsForTask,
|
||||
reservePairedTurnReservation,
|
||||
storeChatMetadata,
|
||||
storeMessage,
|
||||
} from './db.js';
|
||||
import { requireDatabase } from './db/runtime-database.js';
|
||||
import { processLoopGroupMessages } from './message-runtime-dispatch.js';
|
||||
import { advanceLastAgentCursor } from './message-runtime-rules.js';
|
||||
import { hasReviewerLease } from './service-routing.js';
|
||||
import { USER_STOP_REPLY } from './stop-intent.js';
|
||||
import type {
|
||||
Channel,
|
||||
NewMessage,
|
||||
PairedTask,
|
||||
RegisteredGroup,
|
||||
} from './types.js';
|
||||
|
||||
const chatJid = 'dc:stop-room';
|
||||
const assistantName = '오너';
|
||||
|
||||
const group: RegisteredGroup = {
|
||||
name: 'Stop Room',
|
||||
folder: 'stop-room',
|
||||
trigger: '@오너',
|
||||
added_at: '2026-10-01T00:00:00.000Z',
|
||||
requiresTrigger: false,
|
||||
};
|
||||
|
||||
const channel: Channel = {
|
||||
name: 'discord',
|
||||
connect: vi.fn(),
|
||||
sendMessage: vi.fn(),
|
||||
isConnected: vi.fn(() => true),
|
||||
ownsJid: vi.fn(() => true),
|
||||
disconnect: vi.fn(),
|
||||
};
|
||||
|
||||
let messageCounter = 0;
|
||||
|
||||
function postHumanMessage(content: string): NewMessage {
|
||||
messageCounter += 1;
|
||||
storeMessage({
|
||||
id: `msg-${messageCounter}`,
|
||||
chat_jid: chatJid,
|
||||
sender: 'user-1',
|
||||
sender_name: 'User',
|
||||
content,
|
||||
timestamp: new Date(
|
||||
Date.UTC(2026, 9, 1, 0, 0, messageCounter),
|
||||
).toISOString(),
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
});
|
||||
const stored = getMessagesSinceSeq(chatJid, '0', assistantName).find(
|
||||
(message) => message.id === `msg-${messageCounter}`,
|
||||
);
|
||||
if (!stored) throw new Error('stored message not found');
|
||||
return stored;
|
||||
}
|
||||
|
||||
function makeTask(overrides: Partial<PairedTask> = {}): PairedTask {
|
||||
return {
|
||||
id: 'stop-task',
|
||||
chat_jid: chatJid,
|
||||
group_folder: group.folder,
|
||||
owner_service_id: 'claude',
|
||||
reviewer_service_id: 'codex-review',
|
||||
owner_agent_type: 'claude-code',
|
||||
reviewer_agent_type: 'codex',
|
||||
arbiter_agent_type: null,
|
||||
title: null,
|
||||
source_ref: 'HEAD',
|
||||
plan_notes: null,
|
||||
review_requested_at: null,
|
||||
round_trip_count: 1,
|
||||
owner_failure_count: 0,
|
||||
owner_step_done_streak: 0,
|
||||
finalize_step_done_count: 0,
|
||||
task_done_then_user_reopen_count: 0,
|
||||
empty_step_done_streak: 0,
|
||||
status: 'in_review',
|
||||
arbiter_verdict: null,
|
||||
arbiter_requested_at: null,
|
||||
completion_reason: null,
|
||||
created_at: '2026-10-01T00:00:00.000Z',
|
||||
updated_at: '2026-10-01T00:05:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeControls(hasQueuedWork: boolean) {
|
||||
return {
|
||||
hasQueuedWork: vi.fn(() => hasQueuedWork),
|
||||
stopRunningAgent: vi.fn(() => hasQueuedWork),
|
||||
sendReply: vi.fn(async () => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function makeArgs(args: {
|
||||
groupMessages: NewMessage[];
|
||||
lastAgentTimestamps: Record<string, string>;
|
||||
controls: ReturnType<typeof makeControls>;
|
||||
}) {
|
||||
return {
|
||||
chatJid,
|
||||
group,
|
||||
groupMessages: args.groupMessages,
|
||||
channel,
|
||||
assistantName,
|
||||
failureFinalText: 'FAILED',
|
||||
hasImplicitContinuationWindow: vi.fn(() => false),
|
||||
lastAgentTimestamps: args.lastAgentTimestamps,
|
||||
saveState: vi.fn(),
|
||||
timezone: 'Asia/Seoul',
|
||||
executeTurn: vi.fn(),
|
||||
schedulePairedFollowUp: vi.fn(() => true),
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
sendQueuedMessage: vi.fn(() => true),
|
||||
closeStdin: vi.fn(),
|
||||
isRunningMessageTurn: vi.fn(() => args.controls.hasQueuedWork()),
|
||||
roomStopControls: args.controls,
|
||||
labelPairedSenders: vi.fn(
|
||||
(_jid: string, messages: NewMessage[]) => messages,
|
||||
),
|
||||
formatMessages: vi.fn((messages: NewMessage[]) =>
|
||||
messages.map((item) => item.content).join('\n'),
|
||||
),
|
||||
} satisfies Parameters<typeof processLoopGroupMessages>[0];
|
||||
}
|
||||
|
||||
describe('natural-language stop in the message loop', () => {
|
||||
beforeEach(() => {
|
||||
_initTestDatabase();
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(hasReviewerLease).mockReturnValue(false);
|
||||
storeChatMetadata(chatJid, '2026-10-01T00:00:00.000Z', 'Stop Room');
|
||||
});
|
||||
|
||||
it('kills the running agent, consumes the messages and replies once', async () => {
|
||||
const request = postHumanMessage('README 정리해줘');
|
||||
const stop = postHumanMessage('그만해');
|
||||
const controls = makeControls(true);
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(request.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [stop],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(controls.stopRunningAgent).toHaveBeenCalledWith(chatJid);
|
||||
expect(controls.sendReply).toHaveBeenCalledTimes(1);
|
||||
expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY);
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq));
|
||||
expect(args.saveState).toHaveBeenCalled();
|
||||
// The stop message must not start or interrupt into a new turn.
|
||||
expect(args.enqueueMessageCheck).not.toHaveBeenCalled();
|
||||
expect(args.closeStdin).not.toHaveBeenCalled();
|
||||
expect(args.sendQueuedMessage).not.toHaveBeenCalled();
|
||||
|
||||
// A run that finishes later with an older end seq cannot rewind the cursor.
|
||||
advanceLastAgentCursor(
|
||||
lastAgentTimestamps,
|
||||
args.saveState,
|
||||
chatJid,
|
||||
request.seq!,
|
||||
);
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq));
|
||||
});
|
||||
|
||||
it('treats a stop phrase as a normal message when nothing is running or pending', async () => {
|
||||
const stop = postHumanMessage('그만');
|
||||
const controls = makeControls(false);
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(stop.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [stop],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(controls.stopRunningAgent).not.toHaveBeenCalled();
|
||||
expect(controls.sendReply).not.toHaveBeenCalled();
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq! - 1));
|
||||
expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('drops unprocessed requests that are still waiting before the stop', async () => {
|
||||
const request = postHumanMessage('배포 스크립트 고쳐줘');
|
||||
const stop = postHumanMessage('멈춰!');
|
||||
const controls = makeControls(false);
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(request.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [request, stop],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY);
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq));
|
||||
expect(args.enqueueMessageCheck).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still processes a new instruction sent after the stop', async () => {
|
||||
const stop = postHumanMessage('중단');
|
||||
const next = postHumanMessage('대신 테스트만 돌려줘');
|
||||
const controls = makeControls(true);
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(stop.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [stop, next],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(controls.stopRunningAgent).toHaveBeenCalledTimes(1);
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq));
|
||||
expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not stop on messages that carry another instruction', async () => {
|
||||
const message = postHumanMessage('그거 하지 말고 이거 해줘');
|
||||
const controls = makeControls(true);
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(message.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [message],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(controls.stopRunningAgent).not.toHaveBeenCalled();
|
||||
expect(controls.sendReply).not.toHaveBeenCalled();
|
||||
expect(args.closeStdin).toHaveBeenCalledWith('human-message-detected');
|
||||
expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes the open paired task, cancels its turn and releases the lease', async () => {
|
||||
vi.mocked(hasReviewerLease).mockReturnValue(true);
|
||||
const task = makeTask();
|
||||
createPairedTask(task);
|
||||
expect(
|
||||
reservePairedTurnReservation({
|
||||
chatJid,
|
||||
taskId: task.id,
|
||||
taskStatus: task.status,
|
||||
roundTripCount: task.round_trip_count,
|
||||
taskUpdatedAt: task.updated_at,
|
||||
intentKind: 'reviewer-turn',
|
||||
runId: 'run-reviewer',
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
claimPairedTurnReservation({
|
||||
chatJid,
|
||||
taskId: task.id,
|
||||
taskStatus: task.status,
|
||||
roundTripCount: task.round_trip_count,
|
||||
taskUpdatedAt: task.updated_at,
|
||||
intentKind: 'reviewer-turn',
|
||||
runId: 'run-reviewer',
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
const stop = postHumanMessage('<@123456789> 작업 중단해줘');
|
||||
const controls = makeControls(false);
|
||||
const reviewerKey = `${chatJid}:reviewer`;
|
||||
const lastAgentTimestamps: Record<string, string> = {
|
||||
[chatJid]: String(stop.seq! - 1),
|
||||
[reviewerKey]: String(stop.seq! - 1),
|
||||
};
|
||||
const args = makeArgs({
|
||||
groupMessages: [stop],
|
||||
lastAgentTimestamps,
|
||||
controls,
|
||||
});
|
||||
|
||||
await processLoopGroupMessages(args);
|
||||
|
||||
expect(getPairedTaskById(task.id)).toMatchObject({
|
||||
status: 'completed',
|
||||
completion_reason: 'user_stopped',
|
||||
});
|
||||
expect(getPairedTurnsForTask(task.id)).toEqual([
|
||||
expect.objectContaining({ state: 'cancelled' }),
|
||||
]);
|
||||
const leaseCount = requireDatabase()
|
||||
.prepare(
|
||||
'SELECT COUNT(*) AS count FROM paired_task_execution_leases WHERE task_id = ?',
|
||||
)
|
||||
.get(task.id) as { count: number };
|
||||
expect(leaseCount.count).toBe(0);
|
||||
expect(lastAgentTimestamps[chatJid]).toBe(String(stop.seq));
|
||||
expect(lastAgentTimestamps[reviewerKey]).toBe(String(stop.seq));
|
||||
expect(controls.stopRunningAgent).toHaveBeenCalledWith(chatJid);
|
||||
expect(controls.sendReply).toHaveBeenCalledWith(chatJid, USER_STOP_REPLY);
|
||||
expect(args.enqueueMessageCheck).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
234
src/room-stop.ts
Normal file
234
src/room-stop.ts
Normal file
@@ -0,0 +1,234 @@
|
||||
import {
|
||||
cancelPairedTurn,
|
||||
getLatestOpenPairedTaskForChat,
|
||||
getMessagesSinceSeq,
|
||||
getPairedTaskById,
|
||||
getPairedTurnsForTask,
|
||||
releasePairedTaskExecutionLeasesForTask,
|
||||
} from './db.js';
|
||||
import { logger } from './logger.js';
|
||||
import {
|
||||
advanceLastAgentCursor,
|
||||
getProcessableMessages,
|
||||
isExternalHumanMessage,
|
||||
resolveCursorKeyForRole,
|
||||
} from './message-runtime-rules.js';
|
||||
import { transitionPairedTaskStatus } from './paired-task-status.js';
|
||||
import { buildPairedTurnIdentity } from './paired-turn-identity.js';
|
||||
import { hasReviewerLease } from './service-routing.js';
|
||||
import { isStopIntent, USER_STOP_REPLY } from './stop-intent.js';
|
||||
import type {
|
||||
Channel,
|
||||
NewMessage,
|
||||
PairedTask,
|
||||
RegisteredGroup,
|
||||
} from './types.js';
|
||||
|
||||
export const USER_STOP_COMPLETION_REASON = 'user_stopped';
|
||||
|
||||
const OPEN_TURN_STATES = new Set(['queued', 'running', 'delegated']);
|
||||
|
||||
export interface RoomStopControls {
|
||||
/** True when the group queue has a run in progress or work waiting. */
|
||||
hasQueuedWork: (chatJid: string) => boolean;
|
||||
/** Close stdin with the stop reason and kill the room's running agent. */
|
||||
stopRunningAgent: (chatJid: string) => boolean;
|
||||
sendReply: (chatJid: string, text: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export type RoomStopResult =
|
||||
| { stopped: false }
|
||||
| { stopped: true; hasMessagesAfterStop: boolean };
|
||||
|
||||
/** The latest human message in the batch whose whole intent is "stop". */
|
||||
export function findStopRequest(messages: NewMessage[]): NewMessage | null {
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index];
|
||||
if (
|
||||
message.seq != null &&
|
||||
isExternalHumanMessage(message) &&
|
||||
isStopIntent(message.content)
|
||||
) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasPendingHumanMessageBefore(args: {
|
||||
chatJid: string;
|
||||
channel: Channel;
|
||||
assistantName: string;
|
||||
lastAgentTimestamps: Record<string, string>;
|
||||
stopSeq: number;
|
||||
}): boolean {
|
||||
const raw = getMessagesSinceSeq(
|
||||
args.chatJid,
|
||||
args.lastAgentTimestamps[args.chatJid] || '0',
|
||||
args.assistantName,
|
||||
);
|
||||
return getProcessableMessages(args.chatJid, raw, args.channel).some(
|
||||
(message) =>
|
||||
message.seq != null &&
|
||||
message.seq < args.stopSeq &&
|
||||
isExternalHumanMessage(message),
|
||||
);
|
||||
}
|
||||
|
||||
function advanceRoomCursorsPast(args: {
|
||||
chatJid: string;
|
||||
stopSeq: number;
|
||||
lastAgentTimestamps: Record<string, string>;
|
||||
saveState: () => void;
|
||||
}): void {
|
||||
const keys = new Set([args.chatJid]);
|
||||
for (const role of ['reviewer', 'arbiter'] as const) {
|
||||
const key = resolveCursorKeyForRole(args.chatJid, role);
|
||||
if (args.lastAgentTimestamps[key] !== undefined) keys.add(key);
|
||||
}
|
||||
for (const key of keys) {
|
||||
advanceLastAgentCursor(
|
||||
args.lastAgentTimestamps,
|
||||
args.saveState,
|
||||
args.chatJid,
|
||||
args.stopSeq,
|
||||
key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function completeTaskAsStopped(task: PairedTask): boolean {
|
||||
let current: PairedTask | undefined = task;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
if (!current || current.status === 'completed') return false;
|
||||
const transitioned = transitionPairedTaskStatus({
|
||||
taskId: current.id,
|
||||
currentStatus: current.status,
|
||||
nextStatus: 'completed',
|
||||
expectedUpdatedAt: current.updated_at,
|
||||
updatedAt: new Date().toISOString(),
|
||||
patch: { completion_reason: USER_STOP_COMPLETION_REASON },
|
||||
});
|
||||
if (transitioned) return true;
|
||||
current = getPairedTaskById(task.id);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function cancelOpenTurns(taskId: string): number {
|
||||
let cancelled = 0;
|
||||
for (const turn of getPairedTurnsForTask(taskId)) {
|
||||
if (!OPEN_TURN_STATES.has(turn.state)) continue;
|
||||
try {
|
||||
cancelPairedTurn({
|
||||
turnIdentity: buildPairedTurnIdentity({
|
||||
taskId: turn.task_id,
|
||||
taskUpdatedAt: turn.task_updated_at,
|
||||
intentKind: turn.intent_kind,
|
||||
role: turn.role,
|
||||
turnId: turn.turn_id,
|
||||
}),
|
||||
error: 'Stopped by user request.',
|
||||
});
|
||||
cancelled += 1;
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ taskId, turnId: turn.turn_id, err },
|
||||
'Failed to cancel paired turn while stopping room work',
|
||||
);
|
||||
}
|
||||
}
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
function closePairedTaskForStop(task: PairedTask): {
|
||||
completed: boolean;
|
||||
cancelledTurns: number;
|
||||
releasedLeases: number;
|
||||
} {
|
||||
const completed = completeTaskAsStopped(task);
|
||||
const cancelledTurns = cancelOpenTurns(task.id);
|
||||
const releasedLeases = releasePairedTaskExecutionLeasesForTask(task.id);
|
||||
return { completed, cancelledTurns, releasedLeases };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a natural-language stop request ("그만", "멈춰", "stop", ...).
|
||||
*
|
||||
* Acts only when the room has something to stop: a running or queued run, an
|
||||
* open paired task, or unprocessed human messages before the stop message.
|
||||
* Otherwise the message is left alone and handled as a normal message.
|
||||
*/
|
||||
export async function stopRoomWorkIfRequested(args: {
|
||||
chatJid: string;
|
||||
group: RegisteredGroup;
|
||||
channel: Channel;
|
||||
messages: NewMessage[];
|
||||
assistantName: string;
|
||||
lastAgentTimestamps: Record<string, string>;
|
||||
saveState: () => void;
|
||||
controls: RoomStopControls;
|
||||
}): Promise<RoomStopResult> {
|
||||
const { chatJid, controls } = args;
|
||||
const stopMessage = findStopRequest(args.messages);
|
||||
if (!stopMessage || stopMessage.seq == null) return { stopped: false };
|
||||
const stopSeq = stopMessage.seq;
|
||||
|
||||
const openTask = hasReviewerLease(chatJid)
|
||||
? (getLatestOpenPairedTaskForChat(chatJid) ?? null)
|
||||
: null;
|
||||
const hasQueuedWork = controls.hasQueuedWork(chatJid);
|
||||
const hasPendingMessages =
|
||||
!hasQueuedWork &&
|
||||
!openTask &&
|
||||
hasPendingHumanMessageBefore({
|
||||
chatJid,
|
||||
channel: args.channel,
|
||||
assistantName: args.assistantName,
|
||||
lastAgentTimestamps: args.lastAgentTimestamps,
|
||||
stopSeq,
|
||||
});
|
||||
if (!hasQueuedWork && !openTask && !hasPendingMessages) {
|
||||
return { stopped: false };
|
||||
}
|
||||
|
||||
// Consume everything up to and including the stop message first, so no
|
||||
// run that finishes or retries afterwards can re-dispatch it.
|
||||
advanceRoomCursorsPast({
|
||||
chatJid,
|
||||
stopSeq,
|
||||
lastAgentTimestamps: args.lastAgentTimestamps,
|
||||
saveState: args.saveState,
|
||||
});
|
||||
const closedTask = openTask ? closePairedTaskForStop(openTask) : null;
|
||||
const killedProcess = controls.stopRunningAgent(chatJid);
|
||||
|
||||
logger.info(
|
||||
{
|
||||
chatJid,
|
||||
group: args.group.name,
|
||||
groupFolder: args.group.folder,
|
||||
stopSeq,
|
||||
killedProcess,
|
||||
hadQueuedWork: hasQueuedWork,
|
||||
hadPendingMessages: hasPendingMessages,
|
||||
pairedTaskId: openTask?.id ?? null,
|
||||
pairedTaskStatus: openTask?.status ?? null,
|
||||
...(closedTask ?? {}),
|
||||
},
|
||||
'Stopped room work on user request',
|
||||
);
|
||||
|
||||
try {
|
||||
await controls.sendReply(chatJid, USER_STOP_REPLY);
|
||||
} catch (err) {
|
||||
logger.warn({ chatJid, err }, 'Failed to send stop confirmation');
|
||||
}
|
||||
|
||||
return {
|
||||
stopped: true,
|
||||
hasMessagesAfterStop: args.messages.some(
|
||||
(message) => message.seq != null && message.seq > stopSeq,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
extractSessionCommand,
|
||||
handleSessionCommand,
|
||||
isSessionCommandControlMessage,
|
||||
isSessionCommandAllowed,
|
||||
} from './session-commands.js';
|
||||
import type { NewMessage } from './types.js';
|
||||
import type { SessionCommandDeps } from './session-commands.js';
|
||||
|
||||
describe('extractSessionCommand', () => {
|
||||
const trigger = /^@Andy\b/i;
|
||||
|
||||
it('detects bare /compact', () => {
|
||||
expect(extractSessionCommand('/compact', trigger)).toBe('/compact');
|
||||
});
|
||||
|
||||
it('does not treat bot-name prefixes as commands anymore', () => {
|
||||
expect(extractSessionCommand('@Andy /compact', trigger)).toBeNull();
|
||||
});
|
||||
|
||||
it('detects bare /clear', () => {
|
||||
expect(extractSessionCommand('/clear', trigger)).toBe('/clear');
|
||||
});
|
||||
|
||||
it('rejects /compact with extra text', () => {
|
||||
expect(extractSessionCommand('/compact now please', trigger)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects partial matches', () => {
|
||||
expect(extractSessionCommand('/compaction', trigger)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects regular messages', () => {
|
||||
expect(
|
||||
extractSessionCommand('please compact the conversation', trigger),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('handles whitespace', () => {
|
||||
expect(extractSessionCommand(' /compact ', trigger)).toBe('/compact');
|
||||
});
|
||||
|
||||
it('is case-sensitive for the command', () => {
|
||||
expect(extractSessionCommand('/Compact', trigger)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSessionCommandAllowed', () => {
|
||||
it('allows main group regardless of sender', () => {
|
||||
expect(isSessionCommandAllowed(true, false, false)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows trusted/admin sender (is_from_me) in non-main group', () => {
|
||||
expect(isSessionCommandAllowed(false, true, false)).toBe(true);
|
||||
});
|
||||
|
||||
it('allows configured admin sender in non-main group', () => {
|
||||
expect(isSessionCommandAllowed(false, false, true)).toBe(true);
|
||||
});
|
||||
|
||||
it('denies untrusted sender in non-main group', () => {
|
||||
expect(isSessionCommandAllowed(false, false, false)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows trusted sender in main group', () => {
|
||||
expect(isSessionCommandAllowed(true, true, false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSessionCommandControlMessage', () => {
|
||||
it('matches clear confirmation output', () => {
|
||||
expect(
|
||||
isSessionCommandControlMessage(
|
||||
'Current session cleared. The next message will start a new conversation.',
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('matches admin denial output', () => {
|
||||
expect(
|
||||
isSessionCommandControlMessage('Session commands require admin access.'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('does not match regular bot conversation', () => {
|
||||
expect(
|
||||
isSessionCommandControlMessage(
|
||||
'좋네요. 필요해지면 바로 말씀드리겠습니다.',
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeMsg(
|
||||
content: string,
|
||||
overrides: Partial<NewMessage> = {},
|
||||
): NewMessage {
|
||||
return {
|
||||
id: 'msg-1',
|
||||
chat_jid: 'group@test',
|
||||
sender: 'user@test',
|
||||
sender_name: 'User',
|
||||
content,
|
||||
timestamp: '100',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(
|
||||
overrides: Partial<SessionCommandDeps> = {},
|
||||
): SessionCommandDeps {
|
||||
return {
|
||||
sendMessage: vi.fn().mockResolvedValue(undefined),
|
||||
setTyping: vi.fn().mockResolvedValue(undefined),
|
||||
runAgent: vi.fn().mockResolvedValue('success'),
|
||||
closeStdin: vi.fn(),
|
||||
clearSession: vi.fn(),
|
||||
advanceCursor: vi.fn(),
|
||||
formatMessages: vi.fn().mockReturnValue('<formatted>'),
|
||||
isAdminSender: vi.fn().mockReturnValue(false),
|
||||
canSenderInteract: vi.fn().mockReturnValue(true),
|
||||
killProcess: vi.fn().mockReturnValue(false),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const trigger = /^@Andy\b/i;
|
||||
|
||||
describe('handleSessionCommand', () => {
|
||||
it('returns handled:false when no session command found', async () => {
|
||||
const deps = makeDeps();
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('hello')],
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result.handled).toBe(false);
|
||||
});
|
||||
|
||||
it('handles authorized /compact in main group', async () => {
|
||||
const deps = makeDeps();
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/compact')],
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.runAgent).toHaveBeenCalledWith(
|
||||
'/compact',
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(deps.advanceCursor).toHaveBeenCalledWith('100');
|
||||
});
|
||||
|
||||
it('handles authorized /clear without invoking the agent', async () => {
|
||||
const deps = makeDeps();
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/clear')],
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.closeStdin).toHaveBeenCalledTimes(1);
|
||||
expect(deps.clearSession).toHaveBeenCalledTimes(1);
|
||||
expect(deps.advanceCursor).toHaveBeenCalledWith('100');
|
||||
expect(deps.runAgent).not.toHaveBeenCalled();
|
||||
expect(deps.sendMessage).toHaveBeenCalledWith(
|
||||
'Current session cleared. The next message will start a new conversation.',
|
||||
);
|
||||
});
|
||||
|
||||
it('sends denial to interactable sender in non-main group', async () => {
|
||||
const deps = makeDeps();
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/compact', { is_from_me: false })],
|
||||
isMainGroup: false,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.sendMessage).toHaveBeenCalledWith(
|
||||
'Session commands require admin access.',
|
||||
);
|
||||
expect(deps.runAgent).not.toHaveBeenCalled();
|
||||
expect(deps.advanceCursor).toHaveBeenCalledWith('100');
|
||||
});
|
||||
|
||||
it('silently consumes denied command when sender cannot interact', async () => {
|
||||
const deps = makeDeps({
|
||||
canSenderInteract: vi.fn().mockReturnValue(false),
|
||||
});
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/compact', { is_from_me: false })],
|
||||
isMainGroup: false,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.sendMessage).not.toHaveBeenCalled();
|
||||
expect(deps.advanceCursor).toHaveBeenCalledWith('100');
|
||||
});
|
||||
|
||||
it('processes pre-compact messages before /compact', async () => {
|
||||
const deps = makeDeps();
|
||||
const msgs = [
|
||||
makeMsg('summarize this', { timestamp: '99' }),
|
||||
makeMsg('/compact', { timestamp: '100' }),
|
||||
];
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: msgs,
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.formatMessages).toHaveBeenCalledWith([msgs[0]], 'UTC');
|
||||
// Two runAgent calls: pre-compact + /compact
|
||||
expect(deps.runAgent).toHaveBeenCalledTimes(2);
|
||||
expect(deps.runAgent).toHaveBeenCalledWith(
|
||||
'<formatted>',
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(deps.runAgent).toHaveBeenCalledWith(
|
||||
'/compact',
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('allows is_from_me sender in non-main group', async () => {
|
||||
const deps = makeDeps();
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/compact', { is_from_me: true })],
|
||||
isMainGroup: false,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.runAgent).toHaveBeenCalledWith(
|
||||
'/compact',
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('allows configured admin sender in non-main group', async () => {
|
||||
const deps = makeDeps({
|
||||
isAdminSender: vi.fn().mockReturnValue(true),
|
||||
});
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [
|
||||
makeMsg('/clear', { is_from_me: false, sender: 'discord-user-1' }),
|
||||
],
|
||||
isMainGroup: false,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.clearSession).toHaveBeenCalledTimes(1);
|
||||
expect(deps.sendMessage).toHaveBeenCalledWith(
|
||||
'Current session cleared. The next message will start a new conversation.',
|
||||
);
|
||||
});
|
||||
|
||||
it('reports failure when command-stage runAgent returns error without streamed status', async () => {
|
||||
// runAgent resolves 'error' but callback never gets status: 'error'
|
||||
const deps = makeDeps({
|
||||
runAgent: vi.fn().mockImplementation(async (prompt, onOutput) => {
|
||||
await onOutput({ status: 'success', result: null });
|
||||
return 'error';
|
||||
}),
|
||||
});
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: [makeMsg('/compact')],
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: true });
|
||||
expect(deps.sendMessage).toHaveBeenCalledWith(
|
||||
expect.stringContaining('failed'),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns success:false on pre-compact failure with no output', async () => {
|
||||
const deps = makeDeps({ runAgent: vi.fn().mockResolvedValue('error') });
|
||||
const msgs = [
|
||||
makeMsg('summarize this', { timestamp: '99' }),
|
||||
makeMsg('/compact', { timestamp: '100' }),
|
||||
];
|
||||
const result = await handleSessionCommand({
|
||||
missedMessages: msgs,
|
||||
isMainGroup: true,
|
||||
groupName: 'test',
|
||||
triggerPattern: trigger,
|
||||
timezone: 'UTC',
|
||||
deps,
|
||||
});
|
||||
expect(result).toEqual({ handled: true, success: false });
|
||||
expect(deps.sendMessage).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Failed to process'),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,228 +0,0 @@
|
||||
import { getAgentOutputText } from './agent-output.js';
|
||||
import type { NewMessage } from './types.js';
|
||||
import { logger } from './logger.js';
|
||||
import { sanitizeForOutbound } from './router.js';
|
||||
import type { StructuredAgentOutput } from './types.js';
|
||||
|
||||
const SESSION_COMMAND_CONTROL_PATTERNS = [
|
||||
/^Current session cleared\. The next message will start a new conversation\.$/,
|
||||
/^Session commands require admin access\.$/,
|
||||
/^Failed to process messages before \/compact\. Try again\.$/,
|
||||
/^\/compact failed\. The session is unchanged\.$/,
|
||||
/^Conversation compacted\.$/,
|
||||
];
|
||||
|
||||
function normalizeSessionCommandText(
|
||||
content: string,
|
||||
_triggerPattern: RegExp,
|
||||
): string {
|
||||
return content.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a session slash command from a message.
|
||||
* Returns the slash command (e.g., '/compact') or null if not a session command.
|
||||
*/
|
||||
export function extractSessionCommand(
|
||||
content: string,
|
||||
triggerPattern: RegExp,
|
||||
): string | null {
|
||||
const text = normalizeSessionCommandText(content, triggerPattern);
|
||||
if (text === '/compact') return '/compact';
|
||||
if (text === '/clear') return '/clear';
|
||||
if (text === '/stop') return '/stop';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a session command sender is authorized.
|
||||
* Allowed: main group (any sender), or trusted/admin sender in any group.
|
||||
*/
|
||||
export function isSessionCommandAllowed(
|
||||
isMainGroup: boolean,
|
||||
isFromMe: boolean,
|
||||
isAdminSender: boolean = false,
|
||||
): boolean {
|
||||
return isMainGroup || isFromMe || isAdminSender;
|
||||
}
|
||||
|
||||
export function isSessionCommandControlMessage(content: string): boolean {
|
||||
const trimmed = content.trim();
|
||||
return SESSION_COMMAND_CONTROL_PATTERNS.some((pattern) =>
|
||||
pattern.test(trimmed),
|
||||
);
|
||||
}
|
||||
|
||||
/** Minimal agent result interface — matches the subset of AgentOutput used here. */
|
||||
export interface AgentResult {
|
||||
status: 'success' | 'error';
|
||||
result?: string | object | null;
|
||||
output?: StructuredAgentOutput;
|
||||
}
|
||||
|
||||
/** Dependencies injected by the orchestrator. */
|
||||
export interface SessionCommandDeps {
|
||||
sendMessage: (text: string) => Promise<void>;
|
||||
setTyping: (typing: boolean) => Promise<void>;
|
||||
runAgent: (
|
||||
prompt: string,
|
||||
onOutput: (result: AgentResult) => Promise<void>,
|
||||
) => Promise<'success' | 'error'>;
|
||||
closeStdin: () => void;
|
||||
clearSession: (opts?: { allRoles?: boolean }) => void;
|
||||
advanceCursor: (timestamp: string) => void;
|
||||
formatMessages: (msgs: NewMessage[], timezone: string) => string;
|
||||
isAdminSender: (msg: NewMessage) => boolean;
|
||||
/** Whether the denied sender would normally be allowed to interact (for denial messages). */
|
||||
canSenderInteract: (msg: NewMessage) => boolean;
|
||||
/** Reset/complete the active paired task so ping-pong stops. */
|
||||
resetPairedTask?: () => void;
|
||||
/** Kill the currently running agent process for this group. Returns true if a process was killed. */
|
||||
killProcess: () => boolean;
|
||||
}
|
||||
|
||||
function agentResultToText(result: AgentResult): string {
|
||||
const raw = getAgentOutputText({
|
||||
result: result.result ?? null,
|
||||
output: result.output,
|
||||
});
|
||||
return raw ? sanitizeForOutbound(raw) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle session command interception in processGroupMessages.
|
||||
* Scans messages for a session command, handles auth + execution.
|
||||
* Returns { handled: true, success } if a command was found; { handled: false } otherwise.
|
||||
* success=false means the caller should retry (cursor was not advanced).
|
||||
*/
|
||||
export async function handleSessionCommand(opts: {
|
||||
missedMessages: NewMessage[];
|
||||
isMainGroup: boolean;
|
||||
groupName: string;
|
||||
runId?: string;
|
||||
triggerPattern: RegExp;
|
||||
timezone: string;
|
||||
deps: SessionCommandDeps;
|
||||
}): Promise<{ handled: false } | { handled: true; success: boolean }> {
|
||||
const {
|
||||
missedMessages,
|
||||
isMainGroup,
|
||||
groupName,
|
||||
runId,
|
||||
triggerPattern,
|
||||
timezone,
|
||||
deps,
|
||||
} = opts;
|
||||
|
||||
const cmdMsg = missedMessages.find(
|
||||
(m) => extractSessionCommand(m.content, triggerPattern) !== null,
|
||||
);
|
||||
const command = cmdMsg
|
||||
? extractSessionCommand(cmdMsg.content, triggerPattern)
|
||||
: null;
|
||||
if (!command || !cmdMsg) return { handled: false };
|
||||
|
||||
if (
|
||||
!isSessionCommandAllowed(
|
||||
isMainGroup,
|
||||
cmdMsg.is_from_me === true,
|
||||
deps.isAdminSender(cmdMsg),
|
||||
)
|
||||
) {
|
||||
// DENIED: send denial if the sender would normally be allowed to interact,
|
||||
// then silently consume the command by advancing the cursor past it.
|
||||
// Trade-off: other messages in the same batch are also consumed (cursor is
|
||||
// a high-water mark). Acceptable for this narrow edge case.
|
||||
if (deps.canSenderInteract(cmdMsg)) {
|
||||
await deps.sendMessage('Session commands require admin access.');
|
||||
}
|
||||
deps.advanceCursor(cmdMsg.timestamp);
|
||||
return { handled: true, success: true };
|
||||
}
|
||||
|
||||
// AUTHORIZED: process pre-compact messages first, then run the command
|
||||
logger.info({ group: groupName, runId, command }, 'Session command');
|
||||
|
||||
if (command === '/clear') {
|
||||
deps.closeStdin();
|
||||
deps.clearSession({ allRoles: true });
|
||||
deps.resetPairedTask?.();
|
||||
deps.advanceCursor(cmdMsg.timestamp);
|
||||
await deps.sendMessage(
|
||||
'Current session cleared. The next message will start a new conversation.',
|
||||
);
|
||||
return { handled: true, success: true };
|
||||
}
|
||||
|
||||
if (command === '/stop') {
|
||||
const killed = deps.killProcess();
|
||||
deps.resetPairedTask?.();
|
||||
deps.advanceCursor(cmdMsg.timestamp);
|
||||
await deps.sendMessage(
|
||||
killed ? 'Agent stopped.' : 'No agent is currently running in this room.',
|
||||
);
|
||||
return { handled: true, success: true };
|
||||
}
|
||||
|
||||
const cmdIndex = missedMessages.indexOf(cmdMsg);
|
||||
const preCompactMsgs = missedMessages.slice(0, cmdIndex);
|
||||
|
||||
// Send pre-compact messages to the agent so they're in the session context.
|
||||
if (preCompactMsgs.length > 0) {
|
||||
const prePrompt = deps.formatMessages(preCompactMsgs, timezone);
|
||||
let hadPreError = false;
|
||||
let preOutputSent = false;
|
||||
|
||||
const preResult = await deps.runAgent(prePrompt, async (result) => {
|
||||
if (result.status === 'error') hadPreError = true;
|
||||
const text = agentResultToText(result);
|
||||
if (text) {
|
||||
await deps.sendMessage(text);
|
||||
preOutputSent = true;
|
||||
}
|
||||
// Close stdin on session-update marker — emitted after query completes,
|
||||
// so all results (including multi-result runs) are already written.
|
||||
if (result.status === 'success' && result.result === null) {
|
||||
deps.closeStdin();
|
||||
}
|
||||
});
|
||||
|
||||
if (preResult === 'error' || hadPreError) {
|
||||
logger.warn(
|
||||
{ group: groupName, runId },
|
||||
'Pre-compact processing failed, aborting session command',
|
||||
);
|
||||
await deps.sendMessage(
|
||||
`Failed to process messages before ${command}. Try again.`,
|
||||
);
|
||||
if (preOutputSent) {
|
||||
// Output was already sent — don't retry or it will duplicate.
|
||||
// Advance cursor past pre-compact messages, leave command pending.
|
||||
deps.advanceCursor(preCompactMsgs[preCompactMsgs.length - 1].timestamp);
|
||||
return { handled: true, success: true };
|
||||
}
|
||||
return { handled: true, success: false };
|
||||
}
|
||||
}
|
||||
|
||||
// Forward the literal slash command as the prompt (no XML formatting)
|
||||
await deps.setTyping(true);
|
||||
|
||||
let hadCmdError = false;
|
||||
const cmdOutput = await deps.runAgent(command, async (result) => {
|
||||
if (result.status === 'error') hadCmdError = true;
|
||||
const text = agentResultToText(result);
|
||||
if (text) await deps.sendMessage(text);
|
||||
});
|
||||
|
||||
// Advance cursor to the command — messages AFTER it remain pending for next poll.
|
||||
deps.advanceCursor(cmdMsg.timestamp);
|
||||
deps.resetPairedTask?.();
|
||||
await deps.setTyping(false);
|
||||
|
||||
if (cmdOutput === 'error' || hadCmdError) {
|
||||
await deps.sendMessage(`${command} failed. The session is unchanged.`);
|
||||
}
|
||||
|
||||
return { handled: true, success: true };
|
||||
}
|
||||
118
src/stop-intent.test.ts
Normal file
118
src/stop-intent.test.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { isStopIntent } from './stop-intent.js';
|
||||
|
||||
describe('isStopIntent', () => {
|
||||
it.each([
|
||||
'그만',
|
||||
'그만해',
|
||||
'그만해줘',
|
||||
'그만해 줘',
|
||||
'그만해주세요',
|
||||
'그만하자',
|
||||
'그만해요',
|
||||
'그만 좀 해',
|
||||
'그만둬',
|
||||
'멈춰',
|
||||
'멈춰줘',
|
||||
'멈춰 주세요',
|
||||
'멈추자',
|
||||
'중단',
|
||||
'중단해',
|
||||
'중단해줘',
|
||||
'중지',
|
||||
'중지해 주세요',
|
||||
'하지마',
|
||||
'하지 마',
|
||||
'하지마세요',
|
||||
'하지 말아줘',
|
||||
'취소',
|
||||
'취소해',
|
||||
'스톱',
|
||||
'스탑',
|
||||
'작업 중단',
|
||||
'작업 중단해줘',
|
||||
'하던 거 그만해',
|
||||
'다 멈춰',
|
||||
'전부 취소해',
|
||||
'제발 그만',
|
||||
'아 그만해',
|
||||
'그만 제발',
|
||||
'잠깐 멈춰',
|
||||
])('treats the Korean stop phrase %j as a stop request', (text) => {
|
||||
expect(isStopIntent(text)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'stop',
|
||||
'Stop',
|
||||
'STOP',
|
||||
'stop it',
|
||||
'stop now',
|
||||
'please stop',
|
||||
'Stop please',
|
||||
'cancel',
|
||||
'cancel that',
|
||||
'abort',
|
||||
'halt',
|
||||
'ok stop',
|
||||
])('treats the English stop phrase %j as a stop request', (text) => {
|
||||
expect(isStopIntent(text)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'그만!',
|
||||
'그만해.',
|
||||
'멈춰!!',
|
||||
'그만해~',
|
||||
'그만해ㅠㅠ',
|
||||
'중단해ㅜ',
|
||||
'stop!',
|
||||
'stop...',
|
||||
' 그만해 ',
|
||||
'<@123456789> 그만해',
|
||||
'<@!123456789> 멈춰',
|
||||
'그만해 <@123456789>',
|
||||
'@오너 그만',
|
||||
])('ignores mentions and trailing punctuation around %j', (text) => {
|
||||
expect(isStopIntent(text)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'그거 하지 말고 이거 해줘',
|
||||
'중단하지 말고 계속해',
|
||||
'로그인 취소 기능 만들어줘',
|
||||
'주문 취소 API 만들어줘',
|
||||
'그만하고 테스트 돌려줘',
|
||||
'멈춰 있는 서버 다시 켜줘',
|
||||
'그만할까?',
|
||||
'그만?',
|
||||
'취소 버튼이 안 눌려',
|
||||
'그거 하지마',
|
||||
'그만해 그리고 이거 봐줘',
|
||||
'아 그만해 진짜 이거 왜 안돼',
|
||||
'빌드 중단된 이유 알려줘',
|
||||
'그만해ㅋㅋ',
|
||||
'',
|
||||
' ',
|
||||
'그\n만',
|
||||
'그만\n이거 해줘',
|
||||
'<@123> 그만 <@456> 이거 해',
|
||||
])('does not treat the Korean message %j as a stop request', (text) => {
|
||||
expect(isStopIntent(text)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"don't stop",
|
||||
'stop the build and deploy',
|
||||
'cancel the login feature',
|
||||
'how do I stop the server?',
|
||||
'stop?',
|
||||
'please stop using tabs',
|
||||
'cancellation flow',
|
||||
'stopwatch',
|
||||
'unstoppable',
|
||||
])('does not treat the English message %j as a stop request', (text) => {
|
||||
expect(isStopIntent(text)).toBe(false);
|
||||
});
|
||||
});
|
||||
69
src/stop-intent.ts
Normal file
69
src/stop-intent.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Conservative classifier for "stop what you are doing" chat messages.
|
||||
*
|
||||
* A message counts as a stop request only when, after removing bot mentions at
|
||||
* the start or end and trailing punctuation, the whole message is a stop
|
||||
* phrase (optionally wrapped in a filler word such as "아", "제발", "작업").
|
||||
* Anything that carries another instruction ("그거 하지 말고 이거 해줘",
|
||||
* "중단하지 말고 계속해", "로그인 취소 기능 만들어줘") is not a stop request.
|
||||
* When unsure, the answer is "not a stop request".
|
||||
*/
|
||||
|
||||
/** Reply posted after a stop request actually stopped something. */
|
||||
export const USER_STOP_REPLY = '진행 중이던 작업을 중단했습니다.';
|
||||
|
||||
const MAX_STOP_MESSAGE_LENGTH = 40;
|
||||
|
||||
const EDGE_MENTIONS_PATTERN = /^(?:<@[!&]?\d+>\s*)+|(?:\s*<@[!&]?\d+>)+$/g;
|
||||
const ANY_MENTION_PATTERN = /<@[!&]?\d+>/;
|
||||
const LEADING_NAME_MENTION_PATTERN = /^@\S+\s+/;
|
||||
// "?" is deliberately not stripped: "그만할까?" / "stop?" are questions.
|
||||
const TRAILING_NOISE_PATTERN = /[\s.!~…ㅠㅜ;,]+$/u;
|
||||
|
||||
// Words that may surround the stop phrase without changing its meaning.
|
||||
// Matched against the Korean text with all whitespace removed.
|
||||
const KOREAN_PREFIX =
|
||||
'(?:아|야|어|앗|헐|제발|진짜|일단|잠깐만?|그냥|이제|지금|다|전부|모두|작업을?|진행을?|하던거|하던것|하던작업)';
|
||||
const KOREAN_SUFFIX = '(?:제발|좀|진짜)';
|
||||
|
||||
const KOREAN_STOP_CORE = [
|
||||
// 그만 / 그만해 / 그만 좀 해 / 그만해줘 / 그만하자 / 그만둬 ...
|
||||
'그만좀?(?:요|해|해요|해라|하자|하세요|해줘|해줘요|해주세요|해주라|해줄래|둬|둬요|둬라|두자|두세요)?',
|
||||
// 중단 / 중지 / 취소 (+ 해, 해줘, 하자, 시켜 ...)
|
||||
'(?:중단|중지|취소)(?:요|해|해요|해라|하자|하세요|해줘|해줘요|해주세요|해주라|시켜|시켜줘|시켜주세요)?',
|
||||
// 멈춰 / 멈춰줘 / 멈추자 / 멈춤
|
||||
'멈(?:춰|춰요|춰라|춰줘|춰줘요|춰주세요|추자|추세요|춤)',
|
||||
// 하지마 / 하지 마 / 하지마세요 / 하지 말아줘
|
||||
'하지(?:마|마요|마라|마세요|말아줘|말아줘요|말아주세요)',
|
||||
'스톱|스탑',
|
||||
].join('|');
|
||||
|
||||
const KOREAN_STOP_PATTERN = new RegExp(
|
||||
`^${KOREAN_PREFIX}{0,2}(?:${KOREAN_STOP_CORE})${KOREAN_SUFFIX}?$`,
|
||||
'u',
|
||||
);
|
||||
|
||||
const ENGLISH_STOP_PATTERN =
|
||||
/^(?:(?:please|pls|ok|okay|hey|just|oh)\s+)*(?:stop|cancel|abort|halt)(?:\s+(?:it|that|this|now|please|pls|everything|all|working))*$/;
|
||||
|
||||
/**
|
||||
* Strip edge mentions and trailing punctuation, lowercase, and collapse
|
||||
* whitespace. Returns null when the message cannot be a bare stop request
|
||||
* (multi-line, or it mentions someone in the middle).
|
||||
*/
|
||||
function normalizeStopCandidate(content: string): string | null {
|
||||
let text = content.trim();
|
||||
if (text.includes('\n')) return null;
|
||||
text = text.replace(EDGE_MENTIONS_PATTERN, '').trim();
|
||||
if (ANY_MENTION_PATTERN.test(text)) return null;
|
||||
text = text.replace(LEADING_NAME_MENTION_PATTERN, '');
|
||||
text = text.replace(TRAILING_NOISE_PATTERN, '');
|
||||
return text.toLowerCase().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
export function isStopIntent(content: string): boolean {
|
||||
const text = normalizeStopCandidate(content);
|
||||
if (!text || text.length > MAX_STOP_MESSAGE_LENGTH) return false;
|
||||
if (ENGLISH_STOP_PATTERN.test(text)) return true;
|
||||
return KOREAN_STOP_PATTERN.test(text.replace(/\s+/g, ''));
|
||||
}
|
||||
Reference in New Issue
Block a user