feat: keep typing during scheduled tasks and tell waiting users

A group-context scheduled task occupies the room queue, so a human message
sent meanwhile waited silently (up to the whole task run) with no typing
indicator; the room looked unresponsive.

- Scheduled tasks (not CI watchers) hold the room's typing indicator for
  their whole run (DiscordChannel.setTypingHold: typing stays on while any
  hold is active, independent of message-turn setTyping(false)).
- A human message that has to wait behind a running scheduled task gets a
  one-time notice per wait: "지금 예약 작업을 진행하고 있습니다. 이 작업을
  마친 뒤 바로 답변드리겠습니다." (GroupQueue.claimScheduledTaskWaitNotice,
  reset when the waiting messages run).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-10-27 23:12:00 +09:00
parent fdfdd384bf
commit fdd98e9eb8
14 changed files with 323 additions and 1 deletions

View File

@@ -1192,6 +1192,58 @@ describe('setTyping', () => {
expect(mockChannel.sendTyping).not.toHaveBeenCalled();
});
it('keeps typing while a hold is active even after setTyping(false)', async () => {
vi.useFakeTimers();
try {
const channel = new DiscordChannel('test-token', createTestOpts());
await channel.connect();
const mockChannel = {
send: vi.fn(),
sendTyping: vi.fn().mockResolvedValue(undefined),
};
currentClient().channels.fetch.mockResolvedValue(mockChannel);
const jid = 'dc:1234567890123456';
await channel.setTypingHold(jid, 'scheduled-task:t1', true);
await channel.setTyping(jid, true);
await channel.setTyping(jid, false); // message turn ends
mockChannel.sendTyping.mockClear();
await vi.advanceTimersByTimeAsync(8000);
expect(mockChannel.sendTyping).toHaveBeenCalledTimes(1);
await channel.setTypingHold(jid, 'scheduled-task:t1', false);
mockChannel.sendTyping.mockClear();
await vi.advanceTimersByTimeAsync(16000);
expect(mockChannel.sendTyping).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
it('releasing a hold does not stop typing a message turn still wants', async () => {
vi.useFakeTimers();
try {
const channel = new DiscordChannel('test-token', createTestOpts());
await channel.connect();
const mockChannel = {
send: vi.fn(),
sendTyping: vi.fn().mockResolvedValue(undefined),
};
currentClient().channels.fetch.mockResolvedValue(mockChannel);
const jid = 'dc:1234567890123456';
await channel.setTyping(jid, true);
await channel.setTypingHold(jid, 'scheduled-task:t1', true);
await channel.setTypingHold(jid, 'scheduled-task:t1', false);
mockChannel.sendTyping.mockClear();
await vi.advanceTimersByTimeAsync(8000);
expect(mockChannel.sendTyping).toHaveBeenCalledTimes(1);
await channel.setTyping(jid, false);
} finally {
vi.useRealTimers();
}
});
it('does nothing when client is not initialized', async () => {
const opts = createTestOpts();
const channel = new DiscordChannel('test-token', opts);

View File

@@ -177,6 +177,8 @@ export class DiscordChannel implements Channel {
private botToken: string;
private typingIntervals = new Map<string, NodeJS.Timeout>();
private typingGenerations = new Map<string, number>();
private typingRequested = new Set<string>();
private typingHolds = new Map<string, Set<string>>();
private agentTypeFilter?: AgentType;
private receivesInbound: boolean;
private ownsDiscordJids: boolean;
@@ -560,7 +562,42 @@ export class DiscordChannel implements Channel {
}
async setTyping(jid: string, isTyping: boolean): Promise<void> {
if (isTyping) {
this.typingRequested.add(jid);
} else {
this.typingRequested.delete(jid);
}
await this.applyTyping(jid);
}
/**
* Keeps the typing indicator on while any hold is active (e.g. a scheduled
* task run), even if a message turn turns its own typing off meanwhile.
*/
async setTypingHold(
jid: string,
holdId: string,
active: boolean,
): Promise<void> {
const holds = this.typingHolds.get(jid) ?? new Set<string>();
if (active) {
if (holds.has(holdId)) return;
holds.add(holdId);
this.typingHolds.set(jid, holds);
} else {
if (!holds.delete(holdId)) return;
if (holds.size === 0) this.typingHolds.delete(jid);
// Still typing for someone else: leave the running indicator alone.
if (holds.size > 0 || this.typingRequested.has(jid)) return;
}
await this.applyTyping(jid);
}
private async applyTyping(jid: string): Promise<void> {
if (!this.client) return;
const isTyping =
this.typingRequested.has(jid) ||
(this.typingHolds.get(jid)?.size ?? 0) > 0;
const generation = (this.typingGenerations.get(jid) ?? 0) + 1;
this.typingGenerations.set(jid, generation);

View File

@@ -44,6 +44,8 @@ export interface GroupState {
postCloseTermTimer: ReturnType<typeof setTimeout> | null;
postCloseKillTimer: ReturnType<typeof setTimeout> | null;
startedAt: number | null;
/** A "will answer after the scheduled task" notice went out for the human messages now waiting. */
scheduledTaskWaitNoticeSent: boolean;
}
const MAX_RECORDED_DIRECT_TERMINAL_RUNS = 16;
@@ -67,6 +69,7 @@ export function createGroupState(): GroupState {
postCloseTermTimer: null,
postCloseKillTimer: null,
startedAt: null,
scheduledTaskWaitNoticeSent: false,
};
}

View File

@@ -605,6 +605,43 @@ describe('GroupQueue', () => {
expect(taskCallCount).toBe(1);
});
it('claims the scheduled-task wait notice once per wait, only while a task runs', async () => {
let resolveTask!: () => void;
queue.setProcessMessagesFn(vi.fn(async () => true));
expect(queue.claimScheduledTaskWaitNotice('group1@g.us')).toBe(false);
queue.enqueueTask(
'group1@g.us',
'task-1',
() =>
new Promise<void>((resolve) => {
resolveTask = resolve;
}),
);
await vi.advanceTimersByTimeAsync(10);
queue.enqueueMessageCheck('group1@g.us');
expect(queue.claimScheduledTaskWaitNotice('group1@g.us')).toBe(true);
expect(queue.claimScheduledTaskWaitNotice('group1@g.us')).toBe(false);
// Task ends -> waiting messages run -> the next wait gets a fresh notice.
resolveTask();
await vi.advanceTimersByTimeAsync(10);
queue.enqueueTask(
'group1@g.us',
'task-2',
() =>
new Promise<void>((resolve) => {
resolveTask = resolve;
}),
);
await vi.advanceTimersByTimeAsync(10);
expect(queue.claimScheduledTaskWaitNotice('group1@g.us')).toBe(true);
resolveTask();
await vi.advanceTimersByTimeAsync(10);
});
// --- Active runs queue work without preemption ---
it('does not preempt an active agent when a task is queued', async () => {

View File

@@ -218,6 +218,18 @@ export class GroupQueue {
);
}
/**
* True once per wait: a scheduled task occupies this room's queue, so a new
* human message has to wait for it. Reset when the waiting messages run.
*/
claimScheduledTaskWaitNotice(groupJid: string): boolean {
const state = this.getGroup(groupJid);
if (state.runPhase !== 'running_task') return false;
if (state.scheduledTaskWaitNoticeSent) return false;
state.scheduledTaskWaitNoticeSent = true;
return true;
}
registerProcess(
groupJid: string,
proc: ChildProcess,
@@ -540,6 +552,7 @@ export class GroupQueue {
const runId = this.createRunId();
state.currentRunId = runId;
state.pendingMessages = false;
state.scheduledTaskWaitNoticeSent = false;
state.startedAt = Date.now();
transitionRunPhase(state, groupJid, 'running_messages', { runId, reason });
assertRunPhaseInvariants(state, groupJid);

View File

@@ -381,6 +381,9 @@ async function main(): Promise<void> {
deliverFormattedCanonicalMessage(jid, rawText),
sendMessageViaReviewerBot: (jid, rawText) =>
deliverFormattedCanonicalMessage(jid, rawText, 'reviewer'),
setTypingHold: async (jid, holdId, active) => {
await findChannel(channels, jid)?.setTypingHold?.(jid, holdId, active);
},
sendTrackedMessage: (jid, rawText) =>
sendFormattedTrackedChannelMessage(channels, jid, rawText),
editTrackedMessage: (jid, messageId, rawText) =>

View File

@@ -112,6 +112,35 @@ describe('processLoopGroupMessages', () => {
expect(args.saveState).not.toHaveBeenCalled();
});
it('asks for the scheduled-task wait notice after queueing a human message', async () => {
const notifyScheduledTaskWait = vi.fn(async () => {});
const args = defaultArgs({
isRunningMessageTurn: vi.fn(() => false),
notifyScheduledTaskWait,
});
await processLoopGroupMessages(args);
expect(args.enqueueMessageCheck).toHaveBeenCalledTimes(1);
expect(notifyScheduledTaskWait).toHaveBeenCalledWith(chatJid);
});
it('does not ask for the wait notice for bot-only messages', async () => {
hasReviewerLeaseMock.mockReturnValue(true);
getLastHumanMessageTimestampMock.mockReturnValue(timestamp);
const notifyScheduledTaskWait = vi.fn(async () => {});
const args = defaultArgs({
groupMessages: [
message({ sender: 'bot', is_bot_message: true, content: 'review' }),
],
notifyScheduledTaskWait,
});
await processLoopGroupMessages(args);
expect(notifyScheduledTaskWait).not.toHaveBeenCalled();
});
it('does not close stdin for human messages when no message turn is running', async () => {
const args = defaultArgs({
isRunningMessageTurn: vi.fn(() => false),

View File

@@ -238,6 +238,8 @@ export async function processLoopGroupMessages(args: {
sendQueuedMessage: (chatJid: string, text: string) => boolean;
closeStdin: (reason: string) => void;
isRunningMessageTurn: (chatJid: string) => boolean;
/** Tells the room once that its message waits behind a running scheduled task. */
notifyScheduledTaskWait?: (chatJid: string) => Promise<void>;
roomStopControls: RoomStopControls;
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
formatMessages: (messages: NewMessage[], timezone: string) => string;
@@ -313,6 +315,7 @@ export async function processLoopGroupMessages(args: {
},
'Queued human message for a fresh turn instead of piping into active agent',
);
await args.notifyScheduledTaskWait?.(chatJid);
return;
}

View File

@@ -40,6 +40,7 @@ export async function processMessageLoopTick(args: {
sendQueuedMessage: (chatJid: string, text: string) => boolean;
closeStdin: (chatJid: string, reason: string) => void;
isRunningMessageTurn: (chatJid: string) => boolean;
notifyScheduledTaskWait?: (chatJid: string) => Promise<void>;
roomStopControls: RoomStopControls;
labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[];
}): Promise<void> {
@@ -105,6 +106,7 @@ export async function processMessageLoopTick(args: {
sendQueuedMessage: args.sendQueuedMessage,
closeStdin: (reason) => args.closeStdin(chatJid, reason),
isRunningMessageTurn: args.isRunningMessageTurn,
notifyScheduledTaskWait: args.notifyScheduledTaskWait,
roomStopControls: args.roomStopControls,
labelPairedSenders: args.labelPairedSenders,
formatMessages,

View File

@@ -69,6 +69,9 @@ function createStartMessageLoop(args: {
};
}
export const SCHEDULED_TASK_WAIT_NOTICE =
'지금 예약 작업을 진행하고 있습니다. 이 작업을 마친 뒤 바로 답변드리겠습니다.';
function createRoomStopControls(
deps: Pick<MessageRuntimeDeps, 'queue' | 'channels' | 'getRoomBindings'>,
): RoomStopControls {
@@ -229,6 +232,20 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
}),
isRunningMessageTurn: (chatJid) =>
deps.queue.getStatuses([chatJid])[0]?.runPhase === 'running_messages',
notifyScheduledTaskWait: async (chatJid) => {
if (!deps.queue.claimScheduledTaskWaitNotice(chatJid)) return;
try {
await roomStopControls.sendReply(
chatJid,
SCHEDULED_TASK_WAIT_NOTICE,
);
} catch (err) {
logger.warn(
{ chatJid, err },
'Failed to send the scheduled task wait notice',
);
}
},
roomStopControls,
labelPairedSenders: labelPairedRuntimeSenders,
});

View File

@@ -15,6 +15,12 @@ export interface SchedulerDependencies {
ipcDir: string,
) => void;
sendMessage: (jid: string, text: string) => Promise<void>;
/** Keeps the room's typing indicator on while a scheduled task runs. */
setTypingHold?: (
jid: string,
holdId: string,
active: boolean,
) => Promise<void>;
sendMessageViaReviewerBot?: (jid: string, text: string) => Promise<void>;
sendTrackedMessage?: (jid: string, text: string) => Promise<string | null>;
editTrackedMessage?: (

View File

@@ -565,6 +565,78 @@ describe('task scheduler', () => {
expect(task?.last_result).toBe('done');
});
it('holds the room typing indicator for the whole scheduled task run', async () => {
const dueAt = new Date(Date.now() - 60_000).toISOString();
const watchPrompt =
'[BACKGROUND CI WATCH]\n\nWatch target:\nrun 1\n\nCheck instructions:\nCheck.';
for (const [id, prompt] of [
['task-typing', 'continue the work'],
['task-typing-watch', watchPrompt],
]) {
createTask({
id,
group_folder: 'shared-group',
chat_jid: 'shared@g.us',
agent_type: 'codex',
prompt,
schedule_type: 'once',
schedule_value: dueAt,
context_mode: 'group',
next_run: dueAt,
status: 'active',
created_at: '2026-02-22T00:00:00.000Z',
});
}
const events: string[] = [];
runAgentProcessMock.mockImplementationOnce(async () => {
events.push('agent');
return { status: 'success' as const, result: 'done' };
});
const executions: Promise<void>[] = [];
const enqueueTask = vi.fn(
(_groupJid: string, _taskId: string, fn: () => Promise<void>) => {
executions.push(fn());
},
);
const setTypingHold = vi.fn(
async (jid: string, holdId: string, active: boolean) => {
events.push(`${active ? 'on' : 'off'}:${jid}:${holdId}`);
},
);
await runSchedulerTickOnce({
serviceAgentType: 'codex',
roomBindings: () => ({
'shared@g.us': {
name: 'Shared',
folder: 'shared-group',
trigger: '@Codex',
added_at: '2026-02-22T00:00:00.000Z',
agentType: 'codex',
},
}),
getSessions: () => ({}),
queue: { enqueueTask } as any,
onProcess: () => {},
sendMessage: async () => {},
setTypingHold,
});
await Promise.all(executions);
// Only the real task holds typing; the CI watcher stays silent.
expect(setTypingHold).toHaveBeenCalledTimes(2);
expect(events.indexOf('on:shared@g.us:scheduled-task:task-typing')).toBe(
events.indexOf('agent') - 1,
);
expect(events).toContain('off:shared@g.us:scheduled-task:task-typing');
expect(
events.indexOf('off:shared@g.us:scheduled-task:task-typing'),
).toBeGreaterThan(
events.indexOf('on:shared@g.us:scheduled-task:task-typing'),
);
});
it('keeps interval tasks active and reschedules them after an execution error', async () => {
const dueAt = new Date(Date.now() - 60_000).toISOString();
createTask({

View File

@@ -33,7 +33,11 @@ import {
formatSuspensionNotice,
suspendTask,
} from './task-suspension.js';
import { getTaskQueueJid, isGitHubCiTask } from './task-watch-status.js';
import {
getTaskQueueJid,
isGitHubCiTask,
isWatchCiTask,
} from './task-watch-status.js';
import { normalizeAgentOutputPhase, ScheduledTask } from './types.js';
import { resolveGroupIpcPath } from './group-folder.js';
import { schedulePairedFollowUpOnce } from './paired-follow-up-scheduler.js';
@@ -169,9 +173,50 @@ function holdAlignmentAfterClaudeTaskLimit(args: {
);
}
async function setScheduledTaskTyping(
deps: SchedulerDependencies,
task: ScheduledTask,
active: boolean,
): Promise<void> {
if (!deps.setTypingHold) return;
try {
await deps.setTypingHold(
task.chat_jid,
`scheduled-task:${task.id}`,
active,
);
} catch (err) {
logger.debug(
{ taskId: task.id, chatJid: task.chat_jid, active, err },
'Failed to update scheduled task typing indicator',
);
}
}
/**
* Scheduled work shows the typing indicator for its whole run, so the room
* does not look idle while a human message waits behind it. CI watchers are
* background polls with their own status message and stay silent.
*/
async function runTask(
task: ScheduledTask,
deps: SchedulerDependencies,
): Promise<void> {
if (isWatchCiTask(task)) {
await runTaskBody(task, deps);
return;
}
await setScheduledTaskTyping(deps, task, true);
try {
await runTaskBody(task, deps);
} finally {
await setScheduledTaskTyping(deps, task, false);
}
}
async function runTaskBody(
task: ScheduledTask,
deps: SchedulerDependencies,
): Promise<void> {
const startTime = Date.now();
let context: TaskExecutionContext;

View File

@@ -291,6 +291,9 @@ export interface Channel {
disconnect(): Promise<void>;
// Optional: typing indicator. Channels that support it implement it.
setTyping?(jid: string, isTyping: boolean): Promise<void>;
// Optional: keep typing on while a hold (e.g. a scheduled task run) is active,
// independent of setTyping(false) from message turns.
setTypingHold?(jid: string, holdId: string, active: boolean): Promise<void>;
// Optional: edit/delete messages (used by status dashboard and tracked progress cleanup).
editMessage?(jid: string, messageId: string, text: string): Promise<void>;
deleteMessage?(jid: string, messageId: string): Promise<void>;