Compare commits
5 Commits
b1dc38ce62
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae4b21e245 | ||
|
|
0f0f698fb4 | ||
|
|
043e9e71c5 | ||
|
|
5c5942ae21 | ||
|
|
c6afd7ccb8 |
@@ -74,7 +74,8 @@ If the first visible line is not one of these statuses, the output is invalid; d
|
||||
- **DONE** — Legacy alias for **TASK_DONE**. Prefer **TASK_DONE** for new turns
|
||||
- **DONE_WITH_CONCERNS** — Changes required: at least one unresolved P0-P2 finding. List each finding with its severity and the exact fix. This is not an approval
|
||||
- **BLOCKED** — Cannot proceed without user decision
|
||||
- **NEEDS_CONTEXT** — Missing information from user
|
||||
- **NEEDS_CONTEXT** — Missing information that only the user can provide. This ends the task and hands it to the user, so never use it to ask the owner for anything
|
||||
- To get test output, evidence, or a fix from the owner, use **DONE_WITH_CONCERNS** and name exactly what the owner must provide; that sends the task back to the owner
|
||||
|
||||
Do not start with non-status review labels like **APPROVE** or **REVISE**. Use **TASK_DONE** for approval and **DONE_WITH_CONCERNS** for change requests.
|
||||
|
||||
@@ -87,7 +88,7 @@ Do not start with non-status review labels like **APPROVE** or **REVISE**. Use *
|
||||
- Treat `EJCLAW_WORK_DIR` as the canonical verification root for this turn. You may inspect other local paths for context, but final review findings must be re-checked against `EJCLAW_WORK_DIR`
|
||||
- Do not use a different clone, canonical repo path, or cached session path as the sole basis for `BLOCKED`, `DONE_WITH_CONCERNS`, or change requests. If another path disagrees with `EJCLAW_WORK_DIR`, prefer `EJCLAW_WORK_DIR` and explicitly call out the mismatch
|
||||
- When test/typecheck/build/lint evidence is needed, prefer the dedicated verification path (`run_verification`) over assuming the reviewer workspace should execute the full project locally
|
||||
- If direct execution is unavailable, request `run_verification` or owner-provided evidence. Do not present static analysis as completed verification
|
||||
- If direct execution is unavailable, request `run_verification` or owner-provided evidence (via DONE_WITH_CONCERNS). Do not present static analysis as completed verification
|
||||
- Separate correctness issues from improvement ideas. If something is only a better alternative, label it P3 instead of blocking the owner unnecessarily
|
||||
- Stagnation: **Spinning** (same error 3+), **Oscillation** (alternating approaches), **Diminishing returns** (shrinking improvement), **No progress** (discussion without change) — name the pattern and report: **Status**, **Attempted**, **Recommendation**
|
||||
- Implementation, commits, and pushes require agreement from both sides. Either can veto
|
||||
|
||||
@@ -25,6 +25,15 @@ Therefore:
|
||||
- If something genuinely cannot complete within one turn, do not pretend a notification is coming. Finish with a concrete status and explicitly ask the user to send a follow-up message to continue. For recurring polling of CI/scheduled work, use the `schedule_task` / `watch_ci` tools, which DO re-invoke you.
|
||||
- Never leave an intermediate "I'll wait … I'll be notified" planning sentence as your final answer.
|
||||
|
||||
### Wait on a PID, not on `pgrep -f`
|
||||
|
||||
A wait loop like `while pgrep -f "pytest evals"; do sleep 10; done` matches its own shell, whose command line contains the same text. It never sees the job exit and runs until its timeout (2026-11-11: an eval finished at 16:47 but the loop only ended at 16:53, and every later wait lost minutes the same way).
|
||||
|
||||
- Save the PID when you start the job: `nohup <cmd> > "$HOME/.tmp/job.log" 2>&1 & echo $! > "$HOME/.tmp/job.pid"`
|
||||
- Wait on that PID: `pid=$(cat "$HOME/.tmp/job.pid"); while kill -0 "$pid" 2>/dev/null; do sleep 10; done` (in the same shell, `wait "$pid"` is enough)
|
||||
- If you can only match by name, use a pattern that cannot match itself: `pgrep -f "[p]ytest evals"`. This only works if the plain text (`pytest evals`) appears nowhere else in that same command, so do not launch and wait in one command this way
|
||||
- When the loop ends, check the log tail or exit status to make sure the job finished and the loop did not just hit its timeout
|
||||
|
||||
## Media attachments
|
||||
|
||||
When a locally generated image, screenshot, video, audio, or document should appear in Discord, include a `MEDIA:` directive on its own line with an absolute local path:
|
||||
|
||||
@@ -24,6 +24,7 @@ Your output is sent directly to the Discord group.
|
||||
- Prefer reading the current workspace before making assumptions
|
||||
- Modify only what is needed for the task
|
||||
- Verify changes when you can instead of claiming they should work
|
||||
- When waiting for a long job, save its PID at launch and poll with `kill -0 "$pid"`. Do not poll with `pgrep -f "<text>"` from a shell whose own command line contains that text: it matches itself and only exits at its timeout. If you must match by name, use `pgrep -f "[p]ytest evals"`
|
||||
- For CI/status/watch requests that require future follow-up, schedule `watch_ci`
|
||||
- Do not use generic recurring task registration from Codex
|
||||
- If the user wants a reminder or other non-CI recurring task, tell them to ask Claude/클코 to schedule it
|
||||
|
||||
@@ -79,7 +79,7 @@ const server = new McpServer({
|
||||
|
||||
server.tool(
|
||||
'send_message',
|
||||
"Send a message to the user or group immediately while you're still running. Use this for progress updates or to send multiple messages. You can call this multiple times.",
|
||||
"Send a message to the user or group immediately while you're still running. Use this for progress updates. You can call this multiple times: while your previous message is still the newest one in the chat, each call is appended to it by editing it, so send only the new update and do not repeat earlier ones.",
|
||||
{
|
||||
text: z.string().describe('The message text to send'),
|
||||
sender: z
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { execFile } from 'child_process';
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
export { computeVerificationSnapshotId } from '../../../shared/verification-snapshot.js';
|
||||
|
||||
export const VERIFICATION_PROFILES = [
|
||||
@@ -130,17 +130,19 @@ export async function runVerificationRequestDirect(
|
||||
repoRoot: string,
|
||||
request: VerificationRequest,
|
||||
): Promise<VerificationResponse> {
|
||||
const helperPath = path.join(
|
||||
repoRoot,
|
||||
'shared',
|
||||
'verification-request-runner.js',
|
||||
// The helper ships with the EJClaw install, not with the repo under review
|
||||
// (src/ and dist/ both sit three levels below the install root).
|
||||
const helperPath = fileURLToPath(
|
||||
new URL('../../../shared/verification-request-runner.js', import.meta.url),
|
||||
);
|
||||
const helperEnv = buildVerificationHelperEnv();
|
||||
const { stdout, stderr } = await execFileCapture(
|
||||
'bun',
|
||||
[helperPath, repoRoot, JSON.stringify(request)],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
// Not repoRoot: EJClaw's config loader reads `.env` from the cwd, and the
|
||||
// repo under review may have its own `.env`. Commands still run in repoRoot.
|
||||
cwd: path.dirname(helperPath),
|
||||
env: helperEnv,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
async function main() {
|
||||
const [repoDir, requestJson] = process.argv.slice(2);
|
||||
|
||||
@@ -10,8 +7,11 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
const verificationModuleUrl = pathToFileURL(
|
||||
path.join(repoDir, 'src', 'verification.ts'),
|
||||
// Load the verifier from the EJClaw install this helper ships with; repoDir
|
||||
// is only the workspace being verified and need not be an EJClaw checkout.
|
||||
const verificationModuleUrl = new URL(
|
||||
'../src/verification.ts',
|
||||
import.meta.url,
|
||||
).href;
|
||||
const verificationModule = await import(verificationModuleUrl);
|
||||
const request = JSON.parse(requestJson);
|
||||
|
||||
@@ -62,6 +62,12 @@ export interface AgentOutput {
|
||||
};
|
||||
/** Tool calls of the run, reported with the terminal output (Claude runner). */
|
||||
toolUsage?: import('./review-skip.js').AgentToolUsage;
|
||||
/**
|
||||
* Host notice emitted after the paired task state changed (e.g. escalated to
|
||||
* the user). Sent as a separate message even after the turn's final, which
|
||||
* would otherwise drop it.
|
||||
*/
|
||||
postCompletionNotice?: boolean;
|
||||
}
|
||||
|
||||
function readRoomSkillOverridesForRunner(
|
||||
|
||||
@@ -58,6 +58,7 @@ const loginShouldRejectRef = vi.hoisted(() => ({ value: false }));
|
||||
vi.mock('discord.js', () => {
|
||||
const Events = {
|
||||
MessageCreate: 'messageCreate',
|
||||
MessageUpdate: 'messageUpdate',
|
||||
ClientReady: 'ready',
|
||||
Error: 'error',
|
||||
};
|
||||
@@ -231,6 +232,25 @@ async function triggerMessage(message: any) {
|
||||
for (const h of handlers) await h(message);
|
||||
}
|
||||
|
||||
async function triggerMessageUpdate(oldMessage: any, newMessage: any) {
|
||||
const handlers = currentClient().eventHandlers.get('messageUpdate') || [];
|
||||
for (const h of handlers) await h(oldMessage, newMessage);
|
||||
}
|
||||
|
||||
function createEditPair(
|
||||
before: string,
|
||||
after: string,
|
||||
overrides: Parameters<typeof createMessage>[0] = {},
|
||||
) {
|
||||
const editedAt = new Date('2024-01-01T00:05:00.000Z');
|
||||
const oldMessage = { ...createMessage({ ...overrides, content: before }) };
|
||||
const newMessage = {
|
||||
...createMessage({ ...overrides, content: after }),
|
||||
editedAt,
|
||||
};
|
||||
return { oldMessage, newMessage, editedAt };
|
||||
}
|
||||
|
||||
// --- Tests ---
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -1309,3 +1329,161 @@ describe('channel properties', () => {
|
||||
expect(metadata.get('dc:222')?.name).toBe('second-chat');
|
||||
});
|
||||
});
|
||||
|
||||
// --- Message edits ---
|
||||
|
||||
describe('message edit handling', () => {
|
||||
it('delivers a human edit as a new message with the original and edited text', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
const { oldMessage, newMessage, editedAt } = createEditPair(
|
||||
'오늘 날씨 알려줘',
|
||||
'내일 날씨 알려줘',
|
||||
{ messageId: 'msg_042', memberDisplayName: '승한' },
|
||||
);
|
||||
await triggerMessageUpdate(oldMessage, newMessage);
|
||||
|
||||
expect(opts.onMessage).toHaveBeenCalledTimes(1);
|
||||
expect(opts.onMessage).toHaveBeenCalledWith('dc:1234567890123456', {
|
||||
id: `msg_042:edit:${editedAt.getTime()}`,
|
||||
chat_jid: 'dc:1234567890123456',
|
||||
sender: '55512345',
|
||||
sender_name: '승한',
|
||||
content:
|
||||
'[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: 오늘 날씨 알려줘\n수정: 내일 날씨 알려줘',
|
||||
timestamp: editedAt.toISOString(),
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('gives each successive edit of one message its own id', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
const first = createEditPair('a', 'b');
|
||||
await triggerMessageUpdate(first.oldMessage, first.newMessage);
|
||||
const second = createEditPair('b', 'c');
|
||||
second.newMessage.editedAt = new Date('2024-01-01T00:06:00.000Z');
|
||||
await triggerMessageUpdate(second.oldMessage, second.newMessage);
|
||||
|
||||
const ids = vi.mocked(opts.onMessage).mock.calls.map(([, msg]) => msg.id);
|
||||
expect(ids).toHaveLength(2);
|
||||
expect(new Set(ids).size).toBe(2);
|
||||
});
|
||||
|
||||
it('ignores updates whose text did not change (link preview / embed)', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
const { oldMessage, newMessage } = createEditPair(
|
||||
'https://example.com',
|
||||
'https://example.com',
|
||||
);
|
||||
await triggerMessageUpdate(oldMessage, newMessage);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores an embed being generated for a link (edit time unchanged)', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
// Unfurl: Discord adds the embed but leaves edited_timestamp null.
|
||||
const oldMessage = {
|
||||
...createMessage({ content: '이거 봐 https://example.com' }),
|
||||
editedAt: null,
|
||||
embeds: [],
|
||||
};
|
||||
const newMessage = {
|
||||
...createMessage({ content: '이거 봐 https://example.com' }),
|
||||
editedAt: null,
|
||||
embeds: [{ url: 'https://example.com', title: 'Example' }],
|
||||
};
|
||||
await triggerMessageUpdate(oldMessage, newMessage);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores "Remove Embeds" even on a message that was edited before', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
// SUPPRESS_EMBEDS keeps the earlier edited_timestamp. The cached old text
|
||||
// is deliberately different so only the edit-time check can reject it.
|
||||
const editedAt = new Date('2024-01-01T00:05:00.000Z');
|
||||
const oldMessage = {
|
||||
...createMessage({ content: '수정 전 https://example.com' }),
|
||||
editedAt: new Date(editedAt),
|
||||
embeds: [{ url: 'https://example.com' }],
|
||||
};
|
||||
const newMessage = {
|
||||
...createMessage({ content: '수정 후 https://example.com' }),
|
||||
editedAt: new Date(editedAt),
|
||||
embeds: [],
|
||||
flags: { has: (flag: number) => flag === 1 << 2 },
|
||||
};
|
||||
await triggerMessageUpdate(oldMessage, newMessage);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores edits by bots, including its own messages', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
const own = createEditPair('진행 중', '완료', {
|
||||
authorId: '999888777',
|
||||
isBot: true,
|
||||
});
|
||||
await triggerMessageUpdate(own.oldMessage, own.newMessage);
|
||||
hasReviewerLeaseMock.mockReturnValue(true);
|
||||
const other = createEditPair('a', 'b', { authorId: '111', isBot: true });
|
||||
await triggerMessageUpdate(other.oldMessage, other.newMessage);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores uncached (partial) messages and unregistered channels', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel('test-token', opts);
|
||||
await channel.connect();
|
||||
|
||||
const partial = createEditPair('a', 'b');
|
||||
await triggerMessageUpdate(
|
||||
{ ...partial.oldMessage, partial: true, content: null },
|
||||
partial.newMessage,
|
||||
);
|
||||
const unregistered = createEditPair('a', 'b', { channelId: '999' });
|
||||
await triggerMessageUpdate(
|
||||
unregistered.oldMessage,
|
||||
unregistered.newMessage,
|
||||
);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not deliver edits on outbound-only bots', async () => {
|
||||
const opts = createTestOpts();
|
||||
const channel = new DiscordChannel(
|
||||
'test-token',
|
||||
opts,
|
||||
undefined,
|
||||
'discord-review',
|
||||
false,
|
||||
);
|
||||
await channel.connect();
|
||||
|
||||
const { oldMessage, newMessage } = createEditPair('a', 'b');
|
||||
await triggerMessageUpdate(oldMessage, newMessage);
|
||||
|
||||
expect(opts.onMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
GatewayIntentBits,
|
||||
Message,
|
||||
MessageFlags,
|
||||
PartialMessage,
|
||||
TextChannel,
|
||||
} from 'discord.js';
|
||||
|
||||
@@ -22,6 +23,7 @@ import { sanitizeForOutbound } from '../router.js';
|
||||
import { hasReviewerLease } from '../service-routing.js';
|
||||
import type {
|
||||
DeleteRecentMessagesByContentOptions,
|
||||
EditMessageOptions,
|
||||
SendMessageOptions,
|
||||
SendMessageResult,
|
||||
} from '../types.js';
|
||||
@@ -169,6 +171,29 @@ export interface DiscordChannelOpts {
|
||||
roomBindings: () => Record<string, RegisteredGroup>;
|
||||
}
|
||||
|
||||
// An edited message is stored as a new message (own id, new seq) so it is
|
||||
// processed exactly like a freshly sent one; the prefix tells the agent it
|
||||
// replaces an earlier message rather than being a new request.
|
||||
export function formatEditedMessageContent(
|
||||
before: string,
|
||||
after: string,
|
||||
): string {
|
||||
return `[메시지 수정됨] 사용자가 이전 메시지를 수정했습니다.\n원문: ${before || '(내용 없음)'}\n수정: ${after}`;
|
||||
}
|
||||
|
||||
function finishDiscordOutboundText(cleanText: string): string {
|
||||
const cleaned = cleanText
|
||||
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
||||
.replace(/\n{3,}/g, '\n\n') // collapse excessive blank lines
|
||||
.trim()
|
||||
// Convert @username mentions to Discord mention format
|
||||
.replaceAll('@눈쟁이', '<@216851709744513024>');
|
||||
// Markdown escaping already happened in prepareDiscordOutbound (prose
|
||||
// escaped, structured output / fenced code preserved). Here we only
|
||||
// re-sanitize so we don't double-escape the delimiters.
|
||||
return sanitizeForOutbound(cleaned);
|
||||
}
|
||||
|
||||
export class DiscordChannel implements Channel {
|
||||
name = 'discord';
|
||||
|
||||
@@ -223,6 +248,10 @@ export class DiscordChannel implements Channel {
|
||||
await this.handleMessageCreate(message);
|
||||
});
|
||||
|
||||
this.client.on(Events.MessageUpdate, async (oldMessage, newMessage) => {
|
||||
await this.handleMessageUpdate(oldMessage, newMessage);
|
||||
});
|
||||
|
||||
// Handle errors gracefully
|
||||
this.client.on(Events.Error, (err) => {
|
||||
logger.error({ err: err.message }, 'Discord client error');
|
||||
@@ -375,6 +404,60 @@ export class DiscordChannel implements Channel {
|
||||
);
|
||||
}
|
||||
|
||||
private async handleMessageUpdate(
|
||||
oldMessage: Message | PartialMessage,
|
||||
newMessage: Message | PartialMessage,
|
||||
): Promise<void> {
|
||||
if (!this.receivesInbound) return;
|
||||
// Partial = not in the cache (e.g. sent before the bot started): the
|
||||
// original text is unknown, so skip it.
|
||||
if (oldMessage.partial || newMessage.partial) return;
|
||||
// Human edits only: own/other bot edits (streaming progress, reviewer bot)
|
||||
// are not user input.
|
||||
if (newMessage.author.bot) return;
|
||||
// Discord sets a new edited_timestamp only when the author edits the
|
||||
// message. Embed/link-preview generation and "Remove Embeds" (the
|
||||
// SUPPRESS_EMBEDS flag) also fire MessageUpdate but leave it unchanged.
|
||||
const editedAt = newMessage.editedAt;
|
||||
if (!editedAt || editedAt.getTime() === oldMessage.editedAt?.getTime()) {
|
||||
return;
|
||||
}
|
||||
const before = oldMessage.content;
|
||||
const after = newMessage.content;
|
||||
// Same text = not a text edit.
|
||||
if (before === after) return;
|
||||
|
||||
const chatJid = `dc:${newMessage.channelId}`;
|
||||
const group = this.opts.roomBindings()[chatJid];
|
||||
if (!group) return;
|
||||
if (
|
||||
this.agentTypeFilter &&
|
||||
(group.agentType || 'claude-code') !== this.agentTypeFilter
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const senderName =
|
||||
newMessage.member?.displayName ||
|
||||
newMessage.author.displayName ||
|
||||
newMessage.author.username;
|
||||
this.opts.onMessage(chatJid, {
|
||||
id: `${newMessage.id}:edit:${editedAt.getTime()}`,
|
||||
chat_jid: chatJid,
|
||||
sender: newMessage.author.id,
|
||||
sender_name: senderName,
|
||||
content: formatEditedMessageContent(before, after),
|
||||
timestamp: editedAt.toISOString(),
|
||||
is_from_me: false,
|
||||
is_bot_message: false,
|
||||
});
|
||||
|
||||
logger.info(
|
||||
{ chatJid, sender: senderName, messageId: newMessage.id },
|
||||
'Discord message edit stored',
|
||||
);
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
jid: string,
|
||||
text: string,
|
||||
@@ -419,17 +502,7 @@ export class DiscordChannel implements Channel {
|
||||
);
|
||||
}
|
||||
|
||||
let cleaned = outbound.cleanText
|
||||
.replace(/^[ \t]*[•*-][ \t]*$/gm, '') // remove empty bullet lines
|
||||
.replace(/\n{3,}/g, '\n\n') // collapse excessive blank lines
|
||||
.trim();
|
||||
|
||||
// Convert @username mentions to Discord mention format
|
||||
cleaned = cleaned.replaceAll('@눈쟁이', '<@216851709744513024>');
|
||||
// Markdown escaping already happened in prepareDiscordOutbound (prose
|
||||
// escaped, structured output / fenced code preserved). Here we only
|
||||
// re-sanitize so we don't double-escape the delimiters.
|
||||
cleaned = sanitizeForOutbound(cleaned);
|
||||
let cleaned = finishDiscordOutboundText(outbound.cleanText);
|
||||
|
||||
// Surface rejected attachments in the visible message. The MEDIA:
|
||||
// directive was already stripped from the text, so without this the user
|
||||
@@ -806,14 +879,29 @@ export class DiscordChannel implements Channel {
|
||||
});
|
||||
}
|
||||
|
||||
isLatestMessage(jid: string, messageId: string): boolean {
|
||||
const channel = this.client?.channels.cache.get(jid.replace(/^dc:/, ''));
|
||||
return (
|
||||
!!channel &&
|
||||
'lastMessageId' in channel &&
|
||||
channel.lastMessageId === messageId
|
||||
);
|
||||
}
|
||||
|
||||
async editMessage(
|
||||
jid: string,
|
||||
messageId: string,
|
||||
text: string,
|
||||
rawText: string,
|
||||
options: EditMessageOptions = {},
|
||||
): Promise<void> {
|
||||
if (!this.client) {
|
||||
throw new Error('Discord client not initialized');
|
||||
}
|
||||
const text = options.formatAsOutbound
|
||||
? finishDiscordOutboundText(
|
||||
prepareDiscordOutbound(rawText, undefined).cleanText,
|
||||
)
|
||||
: rawText;
|
||||
try {
|
||||
const channelId = jid.replace(/^dc:/, '');
|
||||
const channel = await this.client.channels.fetch(channelId);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { _initTestDatabase } from './db.js';
|
||||
|
||||
import {
|
||||
deliverCanonicalOutboundMessage,
|
||||
@@ -238,3 +240,126 @@ describe('deliverIpcOutboundMessage', () => {
|
||||
expect(deliverWorkItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deliverIpcOutboundMessage live message merge', () => {
|
||||
beforeEach(() => {
|
||||
_initTestDatabase();
|
||||
});
|
||||
|
||||
function makeDiscordLikeChannel() {
|
||||
let nextId = 1;
|
||||
let lastMessageId: string | null = null;
|
||||
const sent: { id: string; text: string }[] = [];
|
||||
const edits: { id: string; text: string }[] = [];
|
||||
let failEdits = false;
|
||||
const channel: Channel = {
|
||||
name: 'discord',
|
||||
connect: async () => {},
|
||||
sendMessage: vi.fn(async (_jid: string, text: string) => {
|
||||
const id = `m${nextId++}`;
|
||||
sent.push({ id, text });
|
||||
lastMessageId = id;
|
||||
return { primaryMessageId: id, messageIds: [id], visible: true };
|
||||
}),
|
||||
editMessage: vi.fn(async (_jid: string, id: string, text: string) => {
|
||||
if (failEdits) throw new Error('Unknown Message');
|
||||
edits.push({ id, text });
|
||||
}),
|
||||
isLatestMessage: (_jid: string, id: string) => lastMessageId === id,
|
||||
isConnected: () => true,
|
||||
ownsJid: () => true,
|
||||
disconnect: async () => {},
|
||||
};
|
||||
return {
|
||||
channel,
|
||||
sent,
|
||||
edits,
|
||||
someoneElsePosted: () => {
|
||||
lastMessageId = `other${nextId++}`;
|
||||
},
|
||||
failEdits: () => {
|
||||
failEdits = true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const send = (jid: string, channel: Channel, text: string, extra = {}) =>
|
||||
deliverIpcOutboundMessage(
|
||||
{ jid, text, senderRole: 'owner', ...extra },
|
||||
{
|
||||
channels: [channel],
|
||||
roomBindings: () => ({ [jid]: makeGroup() }),
|
||||
queue: {},
|
||||
},
|
||||
);
|
||||
|
||||
it('edits consecutive progress updates into one message', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-1', d.channel, '첫 번째 진행 상황');
|
||||
await send('dc:merge-1', d.channel, '두 번째 진행 상황');
|
||||
await send('dc:merge-1', d.channel, '세 번째 진행 상황');
|
||||
|
||||
expect(d.sent).toHaveLength(1);
|
||||
expect(d.edits).toEqual([
|
||||
{ id: 'm1', text: '첫 번째 진행 상황\n\n두 번째 진행 상황' },
|
||||
{
|
||||
id: 'm1',
|
||||
text: '첫 번째 진행 상황\n\n두 번째 진행 상황\n\n세 번째 진행 상황',
|
||||
},
|
||||
]);
|
||||
expect(d.channel.editMessage).toHaveBeenCalledWith(
|
||||
'dc:merge-1',
|
||||
'm1',
|
||||
expect.any(String),
|
||||
{ formatAsOutbound: true },
|
||||
);
|
||||
});
|
||||
|
||||
it('starts a new message once someone else posted after it', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-2', d.channel, '진행 1');
|
||||
d.someoneElsePosted();
|
||||
await send('dc:merge-2', d.channel, '진행 2');
|
||||
await send('dc:merge-2', d.channel, '진행 3');
|
||||
|
||||
expect(d.sent.map((m) => m.text)).toEqual(['진행 1', '진행 2']);
|
||||
expect(d.edits).toEqual([{ id: d.sent[1].id, text: '진행 2\n\n진행 3' }]);
|
||||
});
|
||||
|
||||
it('never merges status verdicts or attachments', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-3', d.channel, '진행 1');
|
||||
await send('dc:merge-3', d.channel, 'TASK_DONE\n완료');
|
||||
await send('dc:merge-3', d.channel, '진행 2');
|
||||
await send('dc:merge-3', d.channel, '스크린샷', {
|
||||
attachments: [{ path: '/tmp/a.png' }],
|
||||
});
|
||||
|
||||
expect(d.sent.map((m) => m.text)).toEqual([
|
||||
'진행 1',
|
||||
'TASK_DONE\n완료',
|
||||
'진행 2',
|
||||
'스크린샷',
|
||||
]);
|
||||
expect(d.edits).toEqual([]);
|
||||
});
|
||||
|
||||
it('starts a new message when the merged text would be too long', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-4', d.channel, 'a'.repeat(1000));
|
||||
await send('dc:merge-4', d.channel, 'b'.repeat(1000));
|
||||
|
||||
expect(d.sent).toHaveLength(2);
|
||||
expect(d.edits).toEqual([]);
|
||||
});
|
||||
|
||||
it('falls back to a new message with only the new text when the edit fails', async () => {
|
||||
const d = makeDiscordLikeChannel();
|
||||
await send('dc:merge-5', d.channel, '진행 1');
|
||||
d.failEdits();
|
||||
const result = await send('dc:merge-5', d.channel, '진행 2');
|
||||
|
||||
expect(result).toBe('delivered');
|
||||
expect(d.sent.map((m) => m.text)).toEqual(['진행 1', '진행 2']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createProducedWorkItem } from './db.js';
|
||||
import { createProducedWorkItem, markWorkItemDelivered } from './db.js';
|
||||
import type { WorkItem } from './db/work-items.js';
|
||||
import { resolveRuntimeAttachmentBaseDirs } from './attachment-base-dirs.js';
|
||||
import { deliverOpenWorkItem } from './message-runtime-delivery.js';
|
||||
@@ -50,6 +50,11 @@ export interface CanonicalOutboundDeliveryArgs {
|
||||
text: string;
|
||||
deliveryRole?: PairedRoomRole;
|
||||
attachments?: OutboundAttachment[];
|
||||
/**
|
||||
* Append to this role's previous message by editing it, as long as that
|
||||
* message is still the newest one in the chat, instead of posting a new one.
|
||||
*/
|
||||
mergeIntoLiveMessage?: boolean;
|
||||
}
|
||||
|
||||
export interface CanonicalOutboundDeliveryDeps {
|
||||
@@ -58,8 +63,23 @@ export interface CanonicalOutboundDeliveryDeps {
|
||||
log?: IpcDeliveryLog;
|
||||
createWorkItem?: typeof createProducedWorkItem;
|
||||
deliverWorkItem?: typeof deliverOpenWorkItem;
|
||||
markDelivered?: typeof markWorkItemDelivered;
|
||||
}
|
||||
|
||||
// Raw-text budget for a merged live message. Discord caps a message at 2000
|
||||
// characters and formatting can add escape characters, so keep headroom.
|
||||
const LIVE_MESSAGE_MAX_LENGTH = 1800;
|
||||
|
||||
interface LiveMessage {
|
||||
messageId: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
// Last mergeable message per chat + delivery role. Repeated send_message
|
||||
// progress updates edit this message instead of stacking new ones; a message
|
||||
// from anyone else in between ends the merge (see Channel.isLatestMessage).
|
||||
const liveMessages = new Map<string, LiveMessage>();
|
||||
|
||||
export type CanonicalOutboundDeliveryResult = 'delivered' | 'queued_retry';
|
||||
|
||||
export type IpcOutboundDeliveryResult =
|
||||
@@ -101,6 +121,24 @@ export async function deliverCanonicalOutboundMessage(
|
||||
'Routed outbound message to canonical work item delivery',
|
||||
);
|
||||
|
||||
const channel = route.channel;
|
||||
const liveKey = `${args.jid}|${args.deliveryRole ?? ''}`;
|
||||
const live = args.mergeIntoLiveMessage ? liveMessages.get(liveKey) : null;
|
||||
liveMessages.delete(liveKey);
|
||||
const mergeable =
|
||||
args.mergeIntoLiveMessage === true &&
|
||||
!args.attachments?.length &&
|
||||
!isTerminalStatusMessage(args.text) &&
|
||||
args.text.length <= LIVE_MESSAGE_MAX_LENGTH;
|
||||
const mergedText =
|
||||
mergeable && live ? `${live.text}\n\n${args.text}` : args.text;
|
||||
const canMerge =
|
||||
mergeable &&
|
||||
!!live &&
|
||||
mergedText.length <= LIVE_MESSAGE_MAX_LENGTH &&
|
||||
!!channel.editMessage &&
|
||||
channel.isLatestMessage?.(args.jid, live.messageId) === true;
|
||||
|
||||
const createWorkItem = deps.createWorkItem ?? createProducedWorkItem;
|
||||
const workItem = createWorkItem({
|
||||
group_folder: group.folder,
|
||||
@@ -113,14 +151,56 @@ export async function deliverCanonicalOutboundMessage(
|
||||
attachments: args.attachments,
|
||||
});
|
||||
|
||||
if (canMerge && live) {
|
||||
try {
|
||||
await channel.editMessage!(args.jid, live.messageId, mergedText, {
|
||||
formatAsOutbound: true,
|
||||
});
|
||||
(deps.markDelivered ?? markWorkItemDelivered)(
|
||||
workItem.id,
|
||||
live.messageId,
|
||||
);
|
||||
liveMessages.set(liveKey, {
|
||||
messageId: live.messageId,
|
||||
text: mergedText,
|
||||
});
|
||||
log.info(
|
||||
{
|
||||
transition: 'outbound:merge-live',
|
||||
chatJid: args.jid,
|
||||
deliveryRole: args.deliveryRole ?? null,
|
||||
messageId: live.messageId,
|
||||
workItemId: workItem.id,
|
||||
},
|
||||
'Appended outbound message to the live message by editing it',
|
||||
);
|
||||
return 'delivered';
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
{
|
||||
chatJid: args.jid,
|
||||
deliveryRole: args.deliveryRole ?? null,
|
||||
messageId: live.messageId,
|
||||
err,
|
||||
},
|
||||
'Failed to edit the live message; sending a new message instead',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const deliverWorkItem = deps.deliverWorkItem ?? deliverOpenWorkItem;
|
||||
const delivered = await deliverWorkItem({
|
||||
channel: route.channel,
|
||||
channel,
|
||||
item: workItem as WorkItem,
|
||||
log,
|
||||
attachmentBaseDirs: resolveRuntimeAttachmentBaseDirs(group),
|
||||
isDuplicateOfLastBotFinal: () => false,
|
||||
openContinuation: () => {},
|
||||
onSentAsNewMessage: (messageId) => {
|
||||
if (mergeable && messageId) {
|
||||
liveMessages.set(liveKey, { messageId, text: args.text });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return delivered ? 'delivered' : 'queued_retry';
|
||||
@@ -169,6 +249,7 @@ export async function deliverIpcOutboundMessage(
|
||||
text: args.text,
|
||||
deliveryRole,
|
||||
attachments: args.attachments,
|
||||
mergeIntoLiveMessage: true,
|
||||
},
|
||||
{
|
||||
channels: deps.channels,
|
||||
|
||||
@@ -328,6 +328,76 @@ describe('createPairedExecutionLifecycle completion handling', () => {
|
||||
'원하시던 .env 위치는 여기에 있습니다.',
|
||||
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
||||
]);
|
||||
expect(outputs.every((o) => o.postCompletionNotice === true)).toBe(true);
|
||||
});
|
||||
|
||||
it('flags the escalation notice so it is sent after the reviewer final', async () => {
|
||||
const outputs: AgentOutput[] = [];
|
||||
const base = {
|
||||
id: 'paired-task-reviewer-escalated',
|
||||
chat_jid: 'group@test',
|
||||
group_folder: 'test-group',
|
||||
owner_service_id: 'claude',
|
||||
reviewer_service_id: 'codex-main',
|
||||
title: null,
|
||||
source_ref: 'HEAD',
|
||||
plan_notes: null,
|
||||
round_trip_count: 1,
|
||||
review_requested_at: '2026-04-09T00:00:00.000Z',
|
||||
arbiter_requested_at: null,
|
||||
created_at: '2026-04-09T00:00:00.000Z',
|
||||
};
|
||||
vi.mocked(db.getPairedTaskById).mockReturnValue({
|
||||
...base,
|
||||
status: 'completed',
|
||||
arbiter_verdict: 'escalate',
|
||||
completion_reason: 'escalated',
|
||||
updated_at: '2026-04-09T00:00:01.000Z',
|
||||
});
|
||||
|
||||
const lifecycle = createPairedExecutionLifecycle({
|
||||
pairedExecutionContext: {
|
||||
task: {
|
||||
...base,
|
||||
status: 'in_review',
|
||||
arbiter_verdict: null,
|
||||
completion_reason: null,
|
||||
updated_at: '2026-04-09T00:00:00.000Z',
|
||||
},
|
||||
workspace: null,
|
||||
envOverrides: {},
|
||||
},
|
||||
pairedTurnIdentity: {
|
||||
turnId:
|
||||
'paired-task-reviewer-escalated:2026-04-09T00:00:00.000Z:reviewer-turn',
|
||||
taskId: 'paired-task-reviewer-escalated',
|
||||
taskUpdatedAt: '2026-04-09T00:00:00.000Z',
|
||||
intentKind: 'reviewer-turn',
|
||||
role: 'reviewer',
|
||||
},
|
||||
completedRole: 'reviewer',
|
||||
chatJid: 'group@test',
|
||||
runId: 'run-reviewer-escalated',
|
||||
enqueueMessageCheck: vi.fn(),
|
||||
onOutput: async (output) => {
|
||||
outputs.push(output);
|
||||
},
|
||||
log,
|
||||
});
|
||||
|
||||
lifecycle.recordFinalOutputBeforeDelivery(
|
||||
'NEEDS_CONTEXT\n배포 대상을 알려 주세요.',
|
||||
);
|
||||
lifecycle.markStatus('succeeded');
|
||||
lifecycle.markSawOutput(true);
|
||||
await lifecycle.asyncFinalize();
|
||||
|
||||
expect(outputs).toEqual([
|
||||
expect.objectContaining({
|
||||
result: '<@216851709744513024> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
postCompletionNotice: true,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('releases an owner turn interrupted by a human message without counting an owner failure', async () => {
|
||||
|
||||
@@ -125,19 +125,27 @@ async function notifyPairedCompletionIfNeeded(args: {
|
||||
const task = args.task;
|
||||
if (!task) return;
|
||||
|
||||
const emit = (text: string): Promise<void> | undefined =>
|
||||
const emit = (
|
||||
text: string,
|
||||
options?: { postCompletionNotice?: boolean },
|
||||
): Promise<void> | undefined =>
|
||||
args.onOutput?.({
|
||||
status: 'success',
|
||||
result: text,
|
||||
output: { visibility: 'public', text },
|
||||
phase: 'final',
|
||||
...(options?.postCompletionNotice ? { postCompletionNotice: true } : {}),
|
||||
});
|
||||
|
||||
// Escalation notice fires for any role's completion that escalated to the user.
|
||||
if (task.status === 'completed' && task.completion_reason === 'escalated') {
|
||||
const sender = getLastHumanMessageSender(args.chatJid);
|
||||
const mention = sender ? `<@${sender}> ` : '';
|
||||
await emit(`${mention}⚠️ 자동 해결 불가 — 확인이 필요합니다.`);
|
||||
// The turn already published its final and released its attempt, so this
|
||||
// must bypass those guards or the user is left with a silent stop.
|
||||
await emit(`${mention}⚠️ 자동 해결 불가 — 확인이 필요합니다.`, {
|
||||
postCompletionNotice: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -151,10 +159,11 @@ async function notifyPairedCompletionIfNeeded(args: {
|
||||
) {
|
||||
const ownerAnswer = getLatestOwnerAnswer(task.id);
|
||||
if (ownerAnswer) {
|
||||
await emit(ownerAnswer);
|
||||
await emit(ownerAnswer, { postCompletionNotice: true });
|
||||
}
|
||||
await emit(
|
||||
'ℹ️ 리뷰어 일시 사용 불가 — 리뷰 없이 owner 답변으로 진행했습니다.',
|
||||
{ postCompletionNotice: true },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ export async function deliverOpenWorkItem(args: {
|
||||
replaceMessageId?: string | null;
|
||||
isDuplicateOfLastBotFinal: (chatJid: string, text: string) => boolean;
|
||||
openContinuation: (chatJid: string) => void;
|
||||
onSentAsNewMessage?: (messageId: string | null) => void;
|
||||
}): Promise<boolean> {
|
||||
const replaceMessageId = args.replaceMessageId ?? null;
|
||||
const attachments = args.item.attachments ?? [];
|
||||
@@ -116,6 +117,7 @@ export async function deliverOpenWorkItem(args: {
|
||||
args.item.result_payload,
|
||||
);
|
||||
markWorkItemDelivered(args.item.id, sendResult?.primaryMessageId ?? null);
|
||||
args.onSentAsNewMessage?.(sendResult?.primaryMessageId ?? null);
|
||||
args.openContinuation(args.item.chat_jid);
|
||||
args.log.info(
|
||||
buildDeliveryLogContext(args.channel, args.item, {
|
||||
|
||||
@@ -105,6 +105,32 @@ describe('message-runtime-final-delivery', () => {
|
||||
},
|
||||
);
|
||||
|
||||
it('still delivers a post-completion notice after direct terminal IPC delivery', async () => {
|
||||
const result = await deliverMessageRuntimeFinalText({
|
||||
text: '⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
chatJid: 'chat-1',
|
||||
runId: 'run-1',
|
||||
channel: makeChannel(),
|
||||
group: makeGroup(),
|
||||
startSeq: 10,
|
||||
endSeq: 11,
|
||||
deliveryRole: 'reviewer',
|
||||
deliveryServiceId: 'codex-main',
|
||||
notice: true,
|
||||
hasDirectTerminalDeliveryForRun: vi.fn(() => true),
|
||||
isDuplicateOfLastBotFinal: vi.fn(() => false),
|
||||
openContinuation: vi.fn(),
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(createProducedWorkItem).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
result_payload: '⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
}),
|
||||
);
|
||||
expect(deliverOpenWorkItem).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('creates and delivers a produced work item with default agent type and attachment roots', async () => {
|
||||
const channel = makeChannel();
|
||||
const isDuplicateOfLastBotFinal = vi.fn(() => false);
|
||||
|
||||
@@ -23,6 +23,8 @@ export async function deliverMessageRuntimeFinalText(args: {
|
||||
deliveryRole: PairedRoomRole | null;
|
||||
deliveryServiceId: string | null;
|
||||
replaceMessageId?: string | null;
|
||||
/** Post-completion host notice: sent even when the run's terminal went via IPC. */
|
||||
notice?: boolean;
|
||||
hasDirectTerminalDeliveryForRun?: (
|
||||
chatJid: string,
|
||||
runId: string,
|
||||
@@ -32,6 +34,7 @@ export async function deliverMessageRuntimeFinalText(args: {
|
||||
openContinuation: (chatJid: string) => void;
|
||||
}): Promise<boolean> {
|
||||
if (
|
||||
!args.notice &&
|
||||
(args.deliveryRole === 'reviewer' || args.deliveryRole === 'arbiter') &&
|
||||
args.hasDirectTerminalDeliveryForRun?.(
|
||||
args.chatJid,
|
||||
|
||||
@@ -121,6 +121,7 @@ interface CreateExecuteTurnDeps {
|
||||
deliveryRole: PairedRoomRole | null;
|
||||
deliveryServiceId: string | null;
|
||||
replaceMessageId?: string | null;
|
||||
notice?: boolean;
|
||||
}) => Promise<boolean>;
|
||||
afterDeliverySuccess?: (args: {
|
||||
chatJid: string;
|
||||
@@ -247,6 +248,7 @@ export function createExecuteTurn(deps: CreateExecuteTurnDeps): ExecuteTurnFn {
|
||||
deliveryRole: resolvedDeliveryRole,
|
||||
deliveryServiceId: resolvedDeliveryServiceId,
|
||||
replaceMessageId: options?.replaceMessageId ?? null,
|
||||
...(options?.notice ? { notice: true } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
|
||||
@@ -150,6 +150,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
||||
deliveryRole,
|
||||
deliveryServiceId,
|
||||
replaceMessageId,
|
||||
notice,
|
||||
}) => {
|
||||
return deliverMessageRuntimeFinalText({
|
||||
text,
|
||||
@@ -164,6 +165,7 @@ export function createMessageRuntime(deps: MessageRuntimeDeps): {
|
||||
deliveryRole,
|
||||
deliveryServiceId,
|
||||
replaceMessageId,
|
||||
notice,
|
||||
hasDirectTerminalDeliveryForRun:
|
||||
deps.queue.hasDirectTerminalDeliveryForRun?.bind(deps.queue),
|
||||
isDuplicateOfLastBotFinal: checkDuplicateOfLastBotFinal,
|
||||
|
||||
@@ -1017,3 +1017,72 @@ describe('MessageTurnController human interruptions', () => {
|
||||
expect(deliverFinalText).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MessageTurnController post-completion notices', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
it('delivers an escalation notice after the reviewer final even though the attempt was released', async () => {
|
||||
const channel = makeChannel();
|
||||
const deliverFinalText = vi.fn().mockResolvedValue(true);
|
||||
let ownsAttempt = true;
|
||||
const controller = new MessageTurnController({
|
||||
chatJid: 'dc:test-room',
|
||||
group: makeGroup(),
|
||||
runId: 'run-reviewer-escalated',
|
||||
channel,
|
||||
idleTimeout: 1_000,
|
||||
failureFinalText: '실패',
|
||||
isClaudeCodeAgent: false,
|
||||
clearSession: vi.fn(),
|
||||
requestClose: vi.fn(),
|
||||
deliverFinalText,
|
||||
canDeliverFinalText: () => ownsAttempt,
|
||||
allowProgressReplayWithoutFinal: false,
|
||||
deliveryRole: 'reviewer',
|
||||
pairedTurnIdentity: makeTurnIdentity(),
|
||||
});
|
||||
|
||||
await controller.start();
|
||||
await controller.handleOutput({
|
||||
status: 'success',
|
||||
phase: 'final',
|
||||
result: 'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||
output: {
|
||||
visibility: 'public',
|
||||
text: 'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||
},
|
||||
});
|
||||
// Completing the paired execution escalates the task and releases the
|
||||
// attempt before the host emits its notice.
|
||||
ownsAttempt = false;
|
||||
// A late runner output must still be dropped.
|
||||
await controller.handleOutput({
|
||||
status: 'success',
|
||||
phase: 'final',
|
||||
result: '늦은 출력',
|
||||
output: { visibility: 'public', text: '늦은 출력' },
|
||||
});
|
||||
await controller.handleOutput({
|
||||
status: 'success',
|
||||
phase: 'final',
|
||||
result: '<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
output: {
|
||||
visibility: 'public',
|
||||
text: '<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
},
|
||||
postCompletionNotice: true,
|
||||
});
|
||||
await controller.finish('success');
|
||||
|
||||
expect(deliverFinalText.mock.calls.map(([text]) => text)).toEqual([
|
||||
'NEEDS_CONTEXT\n검증 출력을 주세요.',
|
||||
'<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
]);
|
||||
expect(deliverFinalText).toHaveBeenLastCalledWith(
|
||||
'<@user-1> ⚠️ 자동 해결 불가 — 확인이 필요합니다.',
|
||||
{ replaceMessageId: null, notice: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,6 +66,8 @@ interface MessageTurnControllerOptions {
|
||||
options?: {
|
||||
attachments?: OutboundAttachment[];
|
||||
replaceMessageId?: string | null;
|
||||
/** A post-completion host notice, not the run's own terminal output. */
|
||||
notice?: boolean;
|
||||
},
|
||||
) => Promise<boolean>;
|
||||
canDeliverFinalText?: () => boolean;
|
||||
@@ -173,6 +175,11 @@ export class MessageTurnController {
|
||||
}
|
||||
|
||||
async handleOutput(result: AgentOutput): Promise<void> {
|
||||
if (result.postCompletionNotice) {
|
||||
await this.deliverPostCompletionNotice(result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.terminalObserved()) {
|
||||
this.log.info(
|
||||
{
|
||||
@@ -871,6 +878,28 @@ export class MessageTurnController {
|
||||
this.latestProgressTextForFinal = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Host notices about the paired task's next state (e.g. escalated to the
|
||||
* user) are produced after this run already completed its paired turn
|
||||
* attempt, so the terminal-final and turn-ownership guards would always drop
|
||||
* them. Send them as a fresh message; the progress state is left untouched.
|
||||
*/
|
||||
private async deliverPostCompletionNotice(
|
||||
result: AgentOutput,
|
||||
): Promise<void> {
|
||||
const raw = getAgentOutputText(result);
|
||||
const text = raw ? sanitizeForOutbound(raw) : null;
|
||||
if (!text) return;
|
||||
const delivered = await this.options.deliverFinalText(text, {
|
||||
replaceMessageId: null,
|
||||
notice: true,
|
||||
});
|
||||
this.logOutboundAudit('post-completion-notice', {
|
||||
textLength: text.length,
|
||||
delivered,
|
||||
});
|
||||
}
|
||||
|
||||
private async publishFailureFinal(): Promise<void> {
|
||||
if (this.terminalObserved()) {
|
||||
return;
|
||||
|
||||
17
src/types.ts
17
src/types.ts
@@ -57,6 +57,14 @@ export interface SendMessageOptions {
|
||||
attachmentBaseDirs?: string[];
|
||||
}
|
||||
|
||||
export interface EditMessageOptions {
|
||||
/**
|
||||
* Render the text exactly like a fresh sendMessage would (markdown
|
||||
* neutralization, link/mention handling) instead of editing it in raw.
|
||||
*/
|
||||
formatAsOutbound?: boolean;
|
||||
}
|
||||
|
||||
export interface SendMessageResult {
|
||||
primaryMessageId: string | null;
|
||||
messageIds: string[];
|
||||
@@ -295,7 +303,14 @@ export interface Channel {
|
||||
// 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>;
|
||||
editMessage?(
|
||||
jid: string,
|
||||
messageId: string,
|
||||
text: string,
|
||||
options?: EditMessageOptions,
|
||||
): Promise<void>;
|
||||
// Optional: whether messageId is still the newest message in the chat.
|
||||
isLatestMessage?(jid: string, messageId: string): boolean;
|
||||
deleteMessage?(jid: string, messageId: string): Promise<void>;
|
||||
deleteRecentMessagesByContent?(
|
||||
jid: string,
|
||||
|
||||
Reference in New Issue
Block a user