From fdd98e9eb8671ce6a463f084087412666e9356fa Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 27 Oct 2026 23:12:00 +0900 Subject: [PATCH] feat: keep typing during scheduled tasks and tell waiting users MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- src/channels/discord.test.ts | 52 ++++++++++++++++++++ src/channels/discord.ts | 37 ++++++++++++++ src/group-queue-state.ts | 3 ++ src/group-queue.test.ts | 37 ++++++++++++++ src/group-queue.ts | 13 +++++ src/index.ts | 3 ++ src/message-runtime-dispatch.test.ts | 29 +++++++++++ src/message-runtime-dispatch.ts | 3 ++ src/message-runtime-loop.ts | 2 + src/message-runtime.ts | 17 +++++++ src/task-scheduler-types.ts | 6 +++ src/task-scheduler.test.ts | 72 ++++++++++++++++++++++++++++ src/task-scheduler.ts | 47 +++++++++++++++++- src/types.ts | 3 ++ 14 files changed, 323 insertions(+), 1 deletion(-) diff --git a/src/channels/discord.test.ts b/src/channels/discord.test.ts index 37c4221..374ceb3 100644 --- a/src/channels/discord.test.ts +++ b/src/channels/discord.test.ts @@ -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); diff --git a/src/channels/discord.ts b/src/channels/discord.ts index 305185b..830e60d 100644 --- a/src/channels/discord.ts +++ b/src/channels/discord.ts @@ -177,6 +177,8 @@ export class DiscordChannel implements Channel { private botToken: string; private typingIntervals = new Map(); private typingGenerations = new Map(); + private typingRequested = new Set(); + private typingHolds = new Map>(); 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 { + 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 { + const holds = this.typingHolds.get(jid) ?? new Set(); + 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 { 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); diff --git a/src/group-queue-state.ts b/src/group-queue-state.ts index 8719b6f..7a13233 100644 --- a/src/group-queue-state.ts +++ b/src/group-queue-state.ts @@ -44,6 +44,8 @@ export interface GroupState { postCloseTermTimer: ReturnType | null; postCloseKillTimer: ReturnType | 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, }; } diff --git a/src/group-queue.test.ts b/src/group-queue.test.ts index d2991d1..e38c9ae 100644 --- a/src/group-queue.test.ts +++ b/src/group-queue.test.ts @@ -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((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((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 () => { diff --git a/src/group-queue.ts b/src/group-queue.ts index ae364c6..2096071 100644 --- a/src/group-queue.ts +++ b/src/group-queue.ts @@ -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); diff --git a/src/index.ts b/src/index.ts index d4f3c56..a424b3f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -381,6 +381,9 @@ async function main(): Promise { 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) => diff --git a/src/message-runtime-dispatch.test.ts b/src/message-runtime-dispatch.test.ts index 7f5cd3e..01d5c80 100644 --- a/src/message-runtime-dispatch.test.ts +++ b/src/message-runtime-dispatch.test.ts @@ -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), diff --git a/src/message-runtime-dispatch.ts b/src/message-runtime-dispatch.ts index c77083b..9f1ed2d 100644 --- a/src/message-runtime-dispatch.ts +++ b/src/message-runtime-dispatch.ts @@ -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; 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; } diff --git a/src/message-runtime-loop.ts b/src/message-runtime-loop.ts index b1a7085..edb02b1 100644 --- a/src/message-runtime-loop.ts +++ b/src/message-runtime-loop.ts @@ -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; roomStopControls: RoomStopControls; labelPairedSenders: (chatJid: string, messages: NewMessage[]) => NewMessage[]; }): Promise { @@ -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, diff --git a/src/message-runtime.ts b/src/message-runtime.ts index 8d96c71..e2bb368 100644 --- a/src/message-runtime.ts +++ b/src/message-runtime.ts @@ -69,6 +69,9 @@ function createStartMessageLoop(args: { }; } +export const SCHEDULED_TASK_WAIT_NOTICE = + '지금 예약 작업을 진행하고 있습니다. 이 작업을 마친 뒤 바로 답변드리겠습니다.'; + function createRoomStopControls( deps: Pick, ): 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, }); diff --git a/src/task-scheduler-types.ts b/src/task-scheduler-types.ts index 1242b42..9acb567 100644 --- a/src/task-scheduler-types.ts +++ b/src/task-scheduler-types.ts @@ -15,6 +15,12 @@ export interface SchedulerDependencies { ipcDir: string, ) => void; sendMessage: (jid: string, text: string) => Promise; + /** Keeps the room's typing indicator on while a scheduled task runs. */ + setTypingHold?: ( + jid: string, + holdId: string, + active: boolean, + ) => Promise; sendMessageViaReviewerBot?: (jid: string, text: string) => Promise; sendTrackedMessage?: (jid: string, text: string) => Promise; editTrackedMessage?: ( diff --git a/src/task-scheduler.test.ts b/src/task-scheduler.test.ts index 65b3815..98e7b84 100644 --- a/src/task-scheduler.test.ts +++ b/src/task-scheduler.test.ts @@ -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[] = []; + const enqueueTask = vi.fn( + (_groupJid: string, _taskId: string, fn: () => Promise) => { + 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({ diff --git a/src/task-scheduler.ts b/src/task-scheduler.ts index 82201d7..bde289f 100644 --- a/src/task-scheduler.ts +++ b/src/task-scheduler.ts @@ -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 { + 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 { + 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 { const startTime = Date.now(); let context: TaskExecutionContext; diff --git a/src/types.ts b/src/types.ts index 4ff32b5..a080198 100644 --- a/src/types.ts +++ b/src/types.ts @@ -291,6 +291,9 @@ export interface Channel { disconnect(): Promise; // Optional: typing indicator. Channels that support it implement it. setTyping?(jid: string, isTyping: boolean): Promise; + // 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; // Optional: edit/delete messages (used by status dashboard and tracked progress cleanup). editMessage?(jid: string, messageId: string, text: string): Promise; deleteMessage?(jid: string, messageId: string): Promise;