fix: make chat.send non-blocking
This commit is contained in:
@@ -9,6 +9,7 @@
|
|||||||
- Agents/OpenAI: fix Responses tool-only → follow-up turn handling (avoid standalone `reasoning` items that trigger 400 “required following item”).
|
- Agents/OpenAI: fix Responses tool-only → follow-up turn handling (avoid standalone `reasoning` items that trigger 400 “required following item”).
|
||||||
- Auth: update Claude Code keychain credentials in-place during refresh sync; share JSON file helpers; add CLI fallback coverage.
|
- Auth: update Claude Code keychain credentials in-place during refresh sync; share JSON file helpers; add CLI fallback coverage.
|
||||||
- Onboarding/Gateway: persist non-interactive gateway token auth in config; add WS wizard + gateway tool-calling regression coverage.
|
- Onboarding/Gateway: persist non-interactive gateway token auth in config; add WS wizard + gateway tool-calling regression coverage.
|
||||||
|
- Gateway/Control UI: make `chat.send` non-blocking, wire Stop to `chat.abort`, and treat `/stop` as an out-of-band abort. (#653)
|
||||||
- CLI: `clawdbot sessions` now includes `elev:*` + `usage:*` flags in the table output.
|
- CLI: `clawdbot sessions` now includes `elev:*` + `usage:*` flags in the table output.
|
||||||
- CLI/Pairing: accept positional provider for `pairing list|approve` (npm-run compatible); update docs/bot hints.
|
- CLI/Pairing: accept positional provider for `pairing list|approve` (npm-run compatible); update docs/bot hints.
|
||||||
- Branding: normalize user-facing “ClawdBot”/“CLAWDBOT” → “Clawdbot” (CLI, status, docs).
|
- Branding: normalize user-facing “ClawdBot”/“CLAWDBOT” → “Clawdbot” (CLI, status, docs).
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
waitForEmbeddedPiRunEnd,
|
waitForEmbeddedPiRunEnd,
|
||||||
} from "../agents/pi-embedded.js";
|
} from "../agents/pi-embedded.js";
|
||||||
import { resolveAgentTimeoutMs } from "../agents/timeout.js";
|
import { resolveAgentTimeoutMs } from "../agents/timeout.js";
|
||||||
|
import { isAbortTrigger } from "../auto-reply/reply/abort.js";
|
||||||
import type { CliDeps } from "../cli/deps.js";
|
import type { CliDeps } from "../cli/deps.js";
|
||||||
import { agentCommand } from "../commands/agent.js";
|
import { agentCommand } from "../commands/agent.js";
|
||||||
import type { HealthSummary } from "../commands/health.js";
|
import type { HealthSummary } from "../commands/health.js";
|
||||||
@@ -764,6 +765,12 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
idempotencyKey: string;
|
idempotencyKey: string;
|
||||||
};
|
};
|
||||||
|
const stopCommand = (() => {
|
||||||
|
const msg = p.message.trim();
|
||||||
|
if (!msg) return false;
|
||||||
|
const normalized = msg.toLowerCase();
|
||||||
|
return normalized === "/stop" || isAbortTrigger(msg);
|
||||||
|
})();
|
||||||
const normalizedAttachments =
|
const normalizedAttachments =
|
||||||
p.attachments?.map((a) => ({
|
p.attachments?.map((a) => ({
|
||||||
type: typeof a?.type === "string" ? a.type : undefined,
|
type: typeof a?.type === "string" ? a.type : undefined,
|
||||||
@@ -818,6 +825,35 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
const clientRunId = p.idempotencyKey;
|
const clientRunId = p.idempotencyKey;
|
||||||
registerAgentRunContext(clientRunId, { sessionKey: p.sessionKey });
|
registerAgentRunContext(clientRunId, { sessionKey: p.sessionKey });
|
||||||
|
|
||||||
|
if (stopCommand) {
|
||||||
|
const runIds: string[] = [];
|
||||||
|
for (const [runId, active] of ctx.chatAbortControllers) {
|
||||||
|
if (active.sessionKey !== p.sessionKey) continue;
|
||||||
|
active.controller.abort();
|
||||||
|
ctx.chatAbortControllers.delete(runId);
|
||||||
|
ctx.chatRunBuffers.delete(runId);
|
||||||
|
ctx.chatDeltaSentAt.delete(runId);
|
||||||
|
ctx.removeChatRun(runId, runId, p.sessionKey);
|
||||||
|
const payload = {
|
||||||
|
runId,
|
||||||
|
sessionKey: p.sessionKey,
|
||||||
|
seq: (ctx.agentRunSeq.get(runId) ?? 0) + 1,
|
||||||
|
state: "aborted" as const,
|
||||||
|
};
|
||||||
|
ctx.broadcast("chat", payload);
|
||||||
|
ctx.bridgeSendToSession(p.sessionKey, "chat", payload);
|
||||||
|
runIds.push(runId);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
payloadJSON: JSON.stringify({
|
||||||
|
ok: true,
|
||||||
|
aborted: runIds.length > 0,
|
||||||
|
runIds,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const cached = ctx.dedupe.get(`chat:${clientRunId}`);
|
const cached = ctx.dedupe.get(`chat:${clientRunId}`);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
if (cached.ok) {
|
if (cached.ok) {
|
||||||
@@ -832,6 +868,17 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeExisting = ctx.chatAbortControllers.get(clientRunId);
|
||||||
|
if (activeExisting) {
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
payloadJSON: JSON.stringify({
|
||||||
|
runId: clientRunId,
|
||||||
|
status: "in_flight",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const abortController = new AbortController();
|
const abortController = new AbortController();
|
||||||
ctx.chatAbortControllers.set(clientRunId, {
|
ctx.chatAbortControllers.set(clientRunId, {
|
||||||
@@ -851,7 +898,11 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await agentCommand(
|
const ackPayload = {
|
||||||
|
runId: clientRunId,
|
||||||
|
status: "started" as const,
|
||||||
|
};
|
||||||
|
void agentCommand(
|
||||||
{
|
{
|
||||||
message: messageWithAttachments,
|
message: messageWithAttachments,
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -865,17 +916,32 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
},
|
},
|
||||||
defaultRuntime,
|
defaultRuntime,
|
||||||
ctx.deps,
|
ctx.deps,
|
||||||
);
|
)
|
||||||
const payload = {
|
.then(() => {
|
||||||
runId: clientRunId,
|
ctx.dedupe.set(`chat:${clientRunId}`, {
|
||||||
status: "ok" as const,
|
ts: Date.now(),
|
||||||
};
|
ok: true,
|
||||||
ctx.dedupe.set(`chat:${clientRunId}`, {
|
payload: { runId: clientRunId, status: "ok" as const },
|
||||||
ts: Date.now(),
|
});
|
||||||
ok: true,
|
})
|
||||||
payload,
|
.catch((err) => {
|
||||||
});
|
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||||
return { ok: true, payloadJSON: JSON.stringify(payload) };
|
ctx.dedupe.set(`chat:${clientRunId}`, {
|
||||||
|
ts: Date.now(),
|
||||||
|
ok: false,
|
||||||
|
payload: {
|
||||||
|
runId: clientRunId,
|
||||||
|
status: "error" as const,
|
||||||
|
summary: String(err),
|
||||||
|
},
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
ctx.chatAbortControllers.delete(clientRunId);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { ok: true, payloadJSON: JSON.stringify(ackPayload) };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -896,8 +962,6 @@ export function createBridgeHandlers(ctx: BridgeHandlersContext) {
|
|||||||
message: String(err),
|
message: String(err),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
} finally {
|
|
||||||
ctx.chatAbortControllers.delete(clientRunId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|||||||
|
|
||||||
import { resolveThinkingDefault } from "../../agents/model-selection.js";
|
import { resolveThinkingDefault } from "../../agents/model-selection.js";
|
||||||
import { resolveAgentTimeoutMs } from "../../agents/timeout.js";
|
import { resolveAgentTimeoutMs } from "../../agents/timeout.js";
|
||||||
|
import { isAbortTrigger } from "../../auto-reply/reply/abort.js";
|
||||||
import { agentCommand } from "../../commands/agent.js";
|
import { agentCommand } from "../../commands/agent.js";
|
||||||
import { mergeSessionEntry, saveSessionStore } from "../../config/sessions.js";
|
import { mergeSessionEntry, saveSessionStore } from "../../config/sessions.js";
|
||||||
import { registerAgentRunContext } from "../../infra/agent-events.js";
|
import { registerAgentRunContext } from "../../infra/agent-events.js";
|
||||||
@@ -157,6 +158,12 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
idempotencyKey: string;
|
idempotencyKey: string;
|
||||||
};
|
};
|
||||||
|
const stopCommand = (() => {
|
||||||
|
const msg = p.message.trim();
|
||||||
|
if (!msg) return false;
|
||||||
|
const normalized = msg.toLowerCase();
|
||||||
|
return normalized === "/stop" || isAbortTrigger(msg);
|
||||||
|
})();
|
||||||
const normalizedAttachments =
|
const normalizedAttachments =
|
||||||
p.attachments?.map((a) => ({
|
p.attachments?.map((a) => ({
|
||||||
type: typeof a?.type === "string" ? a.type : undefined,
|
type: typeof a?.type === "string" ? a.type : undefined,
|
||||||
@@ -223,6 +230,33 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (stopCommand) {
|
||||||
|
const runIds: string[] = [];
|
||||||
|
for (const [runId, active] of context.chatAbortControllers) {
|
||||||
|
if (active.sessionKey !== p.sessionKey) continue;
|
||||||
|
active.controller.abort();
|
||||||
|
context.chatAbortControllers.delete(runId);
|
||||||
|
context.chatRunBuffers.delete(runId);
|
||||||
|
context.chatDeltaSentAt.delete(runId);
|
||||||
|
context.removeChatRun(runId, runId, p.sessionKey);
|
||||||
|
const payload = {
|
||||||
|
runId,
|
||||||
|
sessionKey: p.sessionKey,
|
||||||
|
seq: (context.agentRunSeq.get(runId) ?? 0) + 1,
|
||||||
|
state: "aborted" as const,
|
||||||
|
};
|
||||||
|
context.broadcast("chat", payload);
|
||||||
|
context.bridgeSendToSession(p.sessionKey, "chat", payload);
|
||||||
|
runIds.push(runId);
|
||||||
|
}
|
||||||
|
respond(true, {
|
||||||
|
ok: true,
|
||||||
|
aborted: runIds.length > 0,
|
||||||
|
runIds,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const cached = context.dedupe.get(`chat:${clientRunId}`);
|
const cached = context.dedupe.get(`chat:${clientRunId}`);
|
||||||
if (cached) {
|
if (cached) {
|
||||||
respond(cached.ok, cached.payload, cached.error, {
|
respond(cached.ok, cached.payload, cached.error, {
|
||||||
@@ -231,6 +265,17 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const activeExisting = context.chatAbortControllers.get(clientRunId);
|
||||||
|
if (activeExisting) {
|
||||||
|
respond(
|
||||||
|
true,
|
||||||
|
{ runId: clientRunId, status: "in_flight" as const },
|
||||||
|
undefined,
|
||||||
|
{ cached: true, runId: clientRunId },
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const abortController = new AbortController();
|
const abortController = new AbortController();
|
||||||
context.chatAbortControllers.set(clientRunId, {
|
context.chatAbortControllers.set(clientRunId, {
|
||||||
@@ -250,7 +295,13 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await agentCommand(
|
const ackPayload = {
|
||||||
|
runId: clientRunId,
|
||||||
|
status: "started" as const,
|
||||||
|
};
|
||||||
|
respond(true, ackPayload, undefined, { runId: clientRunId });
|
||||||
|
|
||||||
|
void agentCommand(
|
||||||
{
|
{
|
||||||
message: messageWithAttachments,
|
message: messageWithAttachments,
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -264,17 +315,30 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
},
|
},
|
||||||
defaultRuntime,
|
defaultRuntime,
|
||||||
context.deps,
|
context.deps,
|
||||||
);
|
)
|
||||||
const payload = {
|
.then(() => {
|
||||||
runId: clientRunId,
|
context.dedupe.set(`chat:${clientRunId}`, {
|
||||||
status: "ok" as const,
|
ts: Date.now(),
|
||||||
};
|
ok: true,
|
||||||
context.dedupe.set(`chat:${clientRunId}`, {
|
payload: { runId: clientRunId, status: "ok" as const },
|
||||||
ts: Date.now(),
|
});
|
||||||
ok: true,
|
})
|
||||||
payload,
|
.catch((err) => {
|
||||||
});
|
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||||
respond(true, payload, undefined, { runId: clientRunId });
|
context.dedupe.set(`chat:${clientRunId}`, {
|
||||||
|
ts: Date.now(),
|
||||||
|
ok: false,
|
||||||
|
payload: {
|
||||||
|
runId: clientRunId,
|
||||||
|
status: "error" as const,
|
||||||
|
summary: String(err),
|
||||||
|
},
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
context.chatAbortControllers.delete(clientRunId);
|
||||||
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
const error = errorShape(ErrorCodes.UNAVAILABLE, String(err));
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -292,8 +356,6 @@ export const chatHandlers: GatewayRequestHandlers = {
|
|||||||
runId: clientRunId,
|
runId: clientRunId,
|
||||||
error: formatForLog(err),
|
error: formatForLog(err),
|
||||||
});
|
});
|
||||||
} finally {
|
|
||||||
context.chatAbortControllers.delete(clientRunId);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,6 +17,15 @@ import {
|
|||||||
|
|
||||||
installGatewayTestHooks();
|
installGatewayTestHooks();
|
||||||
|
|
||||||
|
async function waitFor(condition: () => boolean, timeoutMs = 1500) {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (condition()) return;
|
||||||
|
await new Promise((r) => setTimeout(r, 5));
|
||||||
|
}
|
||||||
|
throw new Error("timeout waiting for condition");
|
||||||
|
}
|
||||||
|
|
||||||
describe("gateway server chat", () => {
|
describe("gateway server chat", () => {
|
||||||
test("webchat can chat.send without a mobile node", async () => {
|
test("webchat can chat.send without a mobile node", async () => {
|
||||||
const { server, ws } = await startServerWithClient();
|
const { server, ws } = await startServerWithClient();
|
||||||
@@ -45,6 +54,8 @@ describe("gateway server chat", () => {
|
|||||||
const { server, ws } = await startServerWithClient();
|
const { server, ws } = await startServerWithClient();
|
||||||
await connectOk(ws);
|
await connectOk(ws);
|
||||||
|
|
||||||
|
const spy = vi.mocked(agentCommand);
|
||||||
|
const callsBefore = spy.mock.calls.length;
|
||||||
const res = await rpcReq(ws, "chat.send", {
|
const res = await rpcReq(ws, "chat.send", {
|
||||||
sessionKey: "main",
|
sessionKey: "main",
|
||||||
message: "hello",
|
message: "hello",
|
||||||
@@ -52,9 +63,8 @@ describe("gateway server chat", () => {
|
|||||||
});
|
});
|
||||||
expect(res.ok).toBe(true);
|
expect(res.ok).toBe(true);
|
||||||
|
|
||||||
const call = vi.mocked(agentCommand).mock.calls.at(-1)?.[0] as
|
await waitFor(() => spy.mock.calls.length > callsBefore);
|
||||||
| { timeout?: string }
|
const call = spy.mock.calls.at(-1)?.[0] as { timeout?: string } | undefined;
|
||||||
| undefined;
|
|
||||||
expect(call?.timeout).toBe("123");
|
expect(call?.timeout).toBe("123");
|
||||||
|
|
||||||
ws.close();
|
ws.close();
|
||||||
@@ -65,6 +75,8 @@ describe("gateway server chat", () => {
|
|||||||
const { server, ws } = await startServerWithClient();
|
const { server, ws } = await startServerWithClient();
|
||||||
await connectOk(ws);
|
await connectOk(ws);
|
||||||
|
|
||||||
|
const spy = vi.mocked(agentCommand);
|
||||||
|
const callsBefore = spy.mock.calls.length;
|
||||||
const res = await rpcReq(ws, "chat.send", {
|
const res = await rpcReq(ws, "chat.send", {
|
||||||
sessionKey: "agent:main:subagent:abc",
|
sessionKey: "agent:main:subagent:abc",
|
||||||
message: "hello",
|
message: "hello",
|
||||||
@@ -72,7 +84,8 @@ describe("gateway server chat", () => {
|
|||||||
});
|
});
|
||||||
expect(res.ok).toBe(true);
|
expect(res.ok).toBe(true);
|
||||||
|
|
||||||
const call = vi.mocked(agentCommand).mock.calls.at(-1)?.[0] as
|
await waitFor(() => spy.mock.calls.length > callsBefore);
|
||||||
|
const call = spy.mock.calls.at(-1)?.[0] as
|
||||||
| { sessionKey?: string }
|
| { sessionKey?: string }
|
||||||
| undefined;
|
| undefined;
|
||||||
expect(call?.sessionKey).toBe("agent:main:subagent:abc");
|
expect(call?.sessionKey).toBe("agent:main:subagent:abc");
|
||||||
@@ -607,6 +620,9 @@ describe("gateway server chat", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sendRes = await sendResP;
|
||||||
|
expect(sendRes.ok).toBe(true);
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
const deadline = Date.now() + 1000;
|
const deadline = Date.now() + 1000;
|
||||||
const tick = () => {
|
const tick = () => {
|
||||||
@@ -630,9 +646,6 @@ describe("gateway server chat", () => {
|
|||||||
const abortRes = await abortResP;
|
const abortRes = await abortResP;
|
||||||
expect(abortRes.ok).toBe(true);
|
expect(abortRes.ok).toBe(true);
|
||||||
|
|
||||||
const sendRes = await sendResP;
|
|
||||||
expect(sendRes.ok).toBe(true);
|
|
||||||
|
|
||||||
const evt = await abortedEventP;
|
const evt = await abortedEventP;
|
||||||
expect(evt.payload?.runId).toBe("idem-abort-1");
|
expect(evt.payload?.runId).toBe("idem-abort-1");
|
||||||
expect(evt.payload?.sessionKey).toBe("main");
|
expect(evt.payload?.sessionKey).toBe("main");
|
||||||
@@ -731,6 +744,98 @@ describe("gateway server chat", () => {
|
|||||||
await server.close();
|
await server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
"chat.send treats /stop as an out-of-band abort",
|
||||||
|
{ timeout: 15000 },
|
||||||
|
async () => {
|
||||||
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-gw-"));
|
||||||
|
testState.sessionStorePath = path.join(dir, "sessions.json");
|
||||||
|
await fs.writeFile(
|
||||||
|
testState.sessionStorePath,
|
||||||
|
JSON.stringify(
|
||||||
|
{ main: { sessionId: "sess-main", updatedAt: Date.now() } },
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
"utf-8",
|
||||||
|
);
|
||||||
|
|
||||||
|
const { server, ws } = await startServerWithClient();
|
||||||
|
await connectOk(ws);
|
||||||
|
|
||||||
|
const spy = vi.mocked(agentCommand);
|
||||||
|
const callsBefore = spy.mock.calls.length;
|
||||||
|
spy.mockImplementationOnce(async (opts) => {
|
||||||
|
const signal = (opts as { abortSignal?: AbortSignal }).abortSignal;
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
if (!signal) return resolve();
|
||||||
|
if (signal.aborted) return resolve();
|
||||||
|
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const sendResP = onceMessage(
|
||||||
|
ws,
|
||||||
|
(o) => o.type === "res" && o.id === "send-stop-1",
|
||||||
|
8000,
|
||||||
|
);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "req",
|
||||||
|
id: "send-stop-1",
|
||||||
|
method: "chat.send",
|
||||||
|
params: {
|
||||||
|
sessionKey: "main",
|
||||||
|
message: "hello",
|
||||||
|
idempotencyKey: "idem-stop-run",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const sendRes = await sendResP;
|
||||||
|
expect(sendRes.ok).toBe(true);
|
||||||
|
|
||||||
|
await waitFor(() => spy.mock.calls.length > callsBefore);
|
||||||
|
|
||||||
|
const abortedEventP = onceMessage(
|
||||||
|
ws,
|
||||||
|
(o) =>
|
||||||
|
o.type === "event" &&
|
||||||
|
o.event === "chat" &&
|
||||||
|
o.payload?.state === "aborted" &&
|
||||||
|
o.payload?.runId === "idem-stop-run",
|
||||||
|
8000,
|
||||||
|
);
|
||||||
|
|
||||||
|
const stopResP = onceMessage(
|
||||||
|
ws,
|
||||||
|
(o) => o.type === "res" && o.id === "send-stop-2",
|
||||||
|
8000,
|
||||||
|
);
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: "req",
|
||||||
|
id: "send-stop-2",
|
||||||
|
method: "chat.send",
|
||||||
|
params: {
|
||||||
|
sessionKey: "main",
|
||||||
|
message: "/stop",
|
||||||
|
idempotencyKey: "idem-stop-req",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const stopRes = await stopResP;
|
||||||
|
expect(stopRes.ok).toBe(true);
|
||||||
|
|
||||||
|
const evt = await abortedEventP;
|
||||||
|
expect(evt.payload?.sessionKey).toBe("main");
|
||||||
|
|
||||||
|
expect(spy.mock.calls.length).toBe(callsBefore + 1);
|
||||||
|
|
||||||
|
ws.close();
|
||||||
|
await server.close();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test("chat.abort returns aborted=false for unknown runId", async () => {
|
test("chat.abort returns aborted=false for unknown runId", async () => {
|
||||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-gw-"));
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-gw-"));
|
||||||
testState.sessionStorePath = path.join(dir, "sessions.json");
|
testState.sessionStorePath = path.join(dir, "sessions.json");
|
||||||
@@ -876,6 +981,28 @@ describe("gateway server chat", () => {
|
|||||||
);
|
);
|
||||||
expect(sendRes.ok).toBe(true);
|
expect(sendRes.ok).toBe(true);
|
||||||
|
|
||||||
|
// chat.send returns before the run ends; wait until dedupe is populated
|
||||||
|
// (meaning the run completed and the abort controller was cleared).
|
||||||
|
let completed = false;
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
const again = await rpcReq<{ runId?: string; status?: string }>(
|
||||||
|
ws,
|
||||||
|
"chat.send",
|
||||||
|
{
|
||||||
|
sessionKey: "main",
|
||||||
|
message: "hello",
|
||||||
|
idempotencyKey: "idem-complete-1",
|
||||||
|
timeoutMs: 30_000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (again.ok && again.payload?.status === "ok") {
|
||||||
|
completed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
expect(completed).toBe(true);
|
||||||
|
|
||||||
const abortRes = await rpcReq(ws, "chat.abort", {
|
const abortRes = await rpcReq(ws, "chat.abort", {
|
||||||
sessionKey: "main",
|
sessionKey: "main",
|
||||||
runId: "idem-complete-1",
|
runId: "idem-complete-1",
|
||||||
|
|||||||
@@ -201,6 +201,7 @@ export type AppViewState = {
|
|||||||
handleWhatsAppLogout: () => Promise<void>;
|
handleWhatsAppLogout: () => Promise<void>;
|
||||||
handleTelegramSave: () => Promise<void>;
|
handleTelegramSave: () => Promise<void>;
|
||||||
handleSendChat: (messageOverride?: string, opts?: { restoreDraft?: boolean }) => Promise<void>;
|
handleSendChat: (messageOverride?: string, opts?: { restoreDraft?: boolean }) => Promise<void>;
|
||||||
|
handleAbortChat: () => Promise<void>;
|
||||||
removeQueuedMessage: (id: string) => void;
|
removeQueuedMessage: (id: string) => void;
|
||||||
resetToolStream: () => void;
|
resetToolStream: () => void;
|
||||||
handleLogsScroll: (event: Event) => void;
|
handleLogsScroll: (event: Event) => void;
|
||||||
@@ -493,11 +494,13 @@ export function renderApp(state: AppViewState) {
|
|||||||
...state.settings,
|
...state.settings,
|
||||||
useNewChatLayout: !state.settings.useNewChatLayout,
|
useNewChatLayout: !state.settings.useNewChatLayout,
|
||||||
}),
|
}),
|
||||||
onDraftChange: (next) => (state.chatMessage = next),
|
onDraftChange: (next) => (state.chatMessage = next),
|
||||||
onSend: () => state.handleSendChat(),
|
onSend: () => state.handleSendChat(),
|
||||||
onQueueRemove: (id) => state.removeQueuedMessage(id),
|
canAbort: Boolean(state.chatRunId),
|
||||||
onNewSession: () =>
|
onAbort: () => void state.handleAbortChat(),
|
||||||
state.handleSendChat("/new", { restoreDraft: true }),
|
onQueueRemove: (id) => state.removeQueuedMessage(id),
|
||||||
|
onNewSession: () =>
|
||||||
|
state.handleSendChat("/new", { restoreDraft: true }),
|
||||||
// Sidebar props for tool output viewing
|
// Sidebar props for tool output viewing
|
||||||
sidebarOpen: state.sidebarOpen,
|
sidebarOpen: state.sidebarOpen,
|
||||||
sidebarContent: state.sidebarContent,
|
sidebarContent: state.sidebarContent,
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
loadChatHistory,
|
loadChatHistory,
|
||||||
sendChatMessage,
|
sendChatMessage,
|
||||||
|
abortChatRun,
|
||||||
handleChatEvent,
|
handleChatEvent,
|
||||||
type ChatEventPayload,
|
type ChatEventPayload,
|
||||||
} from "./controllers/chat";
|
} from "./controllers/chat";
|
||||||
@@ -1028,6 +1029,20 @@ export class ClawdbotApp extends LitElement {
|
|||||||
return this.chatSending || Boolean(this.chatRunId);
|
return this.chatSending || Boolean(this.chatRunId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private isChatStopCommand(text: string) {
|
||||||
|
const trimmed = text.trim();
|
||||||
|
if (!trimmed) return false;
|
||||||
|
const normalized = trimmed.toLowerCase();
|
||||||
|
return normalized === "/stop" || normalized === "stop" || normalized === "abort";
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleAbortChat() {
|
||||||
|
if (!this.connected) return;
|
||||||
|
this.chatMessage = "";
|
||||||
|
if (!this.chatRunId) return;
|
||||||
|
await abortChatRun(this);
|
||||||
|
}
|
||||||
|
|
||||||
private enqueueChatMessage(text: string) {
|
private enqueueChatMessage(text: string) {
|
||||||
const trimmed = text.trim();
|
const trimmed = text.trim();
|
||||||
if (!trimmed) return;
|
if (!trimmed) return;
|
||||||
@@ -1053,14 +1068,6 @@ export class ClawdbotApp extends LitElement {
|
|||||||
if (ok) {
|
if (ok) {
|
||||||
this.setLastActiveSessionKey(this.sessionKey);
|
this.setLastActiveSessionKey(this.sessionKey);
|
||||||
}
|
}
|
||||||
if (ok && this.chatRunId) {
|
|
||||||
// chat.send returned (run finished), but we missed the chat final event.
|
|
||||||
this.chatRunId = null;
|
|
||||||
this.chatStream = null;
|
|
||||||
this.chatStreamStartedAt = null;
|
|
||||||
this.resetToolStream();
|
|
||||||
void loadChatHistory(this);
|
|
||||||
}
|
|
||||||
if (ok && opts?.restoreDraft && opts.previousDraft?.trim()) {
|
if (ok && opts?.restoreDraft && opts.previousDraft?.trim()) {
|
||||||
this.chatMessage = opts.previousDraft;
|
this.chatMessage = opts.previousDraft;
|
||||||
}
|
}
|
||||||
@@ -1095,6 +1102,11 @@ export class ClawdbotApp extends LitElement {
|
|||||||
const message = (messageOverride ?? this.chatMessage).trim();
|
const message = (messageOverride ?? this.chatMessage).trim();
|
||||||
if (!message) return;
|
if (!message) return;
|
||||||
|
|
||||||
|
if (this.isChatStopCommand(message)) {
|
||||||
|
await this.handleAbortChat();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (messageOverride == null) {
|
if (messageOverride == null) {
|
||||||
this.chatMessage = "";
|
this.chatMessage = "";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,6 +92,22 @@ export async function sendChatMessage(state: ChatState, message: string): Promis
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function abortChatRun(state: ChatState): Promise<boolean> {
|
||||||
|
if (!state.client || !state.connected) return false;
|
||||||
|
const runId = state.chatRunId;
|
||||||
|
if (!runId) return false;
|
||||||
|
try {
|
||||||
|
await state.client.request("chat.abort", {
|
||||||
|
sessionKey: state.sessionKey,
|
||||||
|
runId,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
state.lastError = String(err);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function handleChatEvent(
|
export function handleChatEvent(
|
||||||
state: ChatState,
|
state: ChatState,
|
||||||
payload?: ChatEventPayload,
|
payload?: ChatEventPayload,
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export type ChatProps = {
|
|||||||
thinkingLevel: string | null;
|
thinkingLevel: string | null;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
sending: boolean;
|
sending: boolean;
|
||||||
|
canAbort?: boolean;
|
||||||
messages: unknown[];
|
messages: unknown[];
|
||||||
toolMessages: unknown[];
|
toolMessages: unknown[];
|
||||||
stream: string | null;
|
stream: string | null;
|
||||||
@@ -52,6 +53,7 @@ export type ChatProps = {
|
|||||||
onToggleLayout?: () => void;
|
onToggleLayout?: () => void;
|
||||||
onDraftChange: (next: string) => void;
|
onDraftChange: (next: string) => void;
|
||||||
onSend: () => void;
|
onSend: () => void;
|
||||||
|
onAbort?: () => void;
|
||||||
onQueueRemove: (id: string) => void;
|
onQueueRemove: (id: string) => void;
|
||||||
onNewSession: () => void;
|
onNewSession: () => void;
|
||||||
onOpenSidebar?: (content: string) => void;
|
onOpenSidebar?: (content: string) => void;
|
||||||
@@ -61,7 +63,7 @@ export type ChatProps = {
|
|||||||
|
|
||||||
export function renderChat(props: ChatProps) {
|
export function renderChat(props: ChatProps) {
|
||||||
const canCompose = props.connected;
|
const canCompose = props.connected;
|
||||||
const isBusy = props.sending || Boolean(props.stream);
|
const isBusy = props.sending || props.stream !== null;
|
||||||
const activeSession = props.sessions?.sessions?.find(
|
const activeSession = props.sessions?.sessions?.find(
|
||||||
(row) => row.key === props.sessionKey,
|
(row) => row.key === props.sessionKey,
|
||||||
);
|
);
|
||||||
@@ -222,6 +224,17 @@ export function renderChat(props: ChatProps) {
|
|||||||
>
|
>
|
||||||
New session
|
New session
|
||||||
</button>
|
</button>
|
||||||
|
${props.onAbort
|
||||||
|
? html`
|
||||||
|
<button
|
||||||
|
class="btn danger"
|
||||||
|
?disabled=${!props.connected || !isBusy || props.canAbort === false}
|
||||||
|
@click=${props.onAbort}
|
||||||
|
>
|
||||||
|
Stop
|
||||||
|
</button>
|
||||||
|
`
|
||||||
|
: nothing}
|
||||||
<button
|
<button
|
||||||
class="btn primary"
|
class="btn primary"
|
||||||
?disabled=${!props.connected}
|
?disabled=${!props.connected}
|
||||||
|
|||||||
Reference in New Issue
Block a user