Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Merge remote-tracking branch 'origin/main' into feat/telegram-channel
Naiyuan Qing0895d42d3b5b
diff --cc apps/desktop/electron/ipc/hub.tsindex ad1725dba1,f71fe7f7d4..1e5446cecd--- a/apps/desktop/electron/ipc/hub.ts+++ b/apps/desktop/electron/ipc/hub.ts@@@ -282,6 -281,17 +282,7 @@@ export function registerHubIpcHandlers(return}- // Agent error events: forward so the UI can display them- if (event.type === 'agent_error') {- safeLog(`[IPC] Sending agent_error event to renderer: ${(event as { message: string }).message}`)- mainWindowRef.webContents.send('localChat:event', {- agentId,- streamId: null,- event,- })- return- }+// Filter events same as Hub.consumeAgent()const maybeMessage = (event as { message?: { role?: string } }).messageconst isAssistantMessage = maybeMessage?.role === 'assistant'diff --cc packages/hooks/src/use-gateway-chat.tsindex 1871de28fe,4613bbfbab..0986c7bbd4--- a/packages/hooks/src/use-gateway-chat.ts+++ b/packages/hooks/src/use-gateway-chat.ts@@@ -50,12 -50,6 +50,12 @@@ export function useGatewayChat({ clientclient.onMessage((msg) => {if (msg.action === StreamAction) {const payload = msg.payload as StreamPayload;+ if (payload.event.type === "agent_error") {- const errorMsg = (payload.event as { error?: string }).error ?? "Unknown error";++ const errorMsg = (payload.event as { message?: string }).message ?? "Unknown error";+ chat.setError({ code: "AGENT_ERROR", message: errorMsg });+ setIsLoading(false);+ return;+ }chat.handleStream(payload);if (payload.event.type === "message_start") setIsLoading(true);if (payload.event.type === "message_end") setIsLoading(false);diff --cc packages/ui/src/components/chat-view.tsxindex 07c5a19711,b47edf0b0d..dcdded48c2--- a/packages/ui/src/components/chat-view.tsx+++ b/packages/ui/src/components/chat-view.tsx@@@ -219,21 -221,29 +222,33 @@@ export function ChatView({error && (<div className="container px-4" role="alert" aria-live="polite"><div className="rounded-lg bg-destructive/5 border border-destructive/15 text-xs px-3 py-2 flex items-center justify-between gap-3">- <span className="text-foreground leading-snug">{error.message}</span>+ <span className="text-foreground leading-snug">+ <MemoizedMarkdown mode="minimal" id={`error-${error.code}`}>+ {error.message}+ </MemoizedMarkdown>+ </span>- {onDisconnect && (- <Button- variant="destructive"- size="sm"- onClick={onDisconnect}- className="shrink-0 text-xs h-7 px-2.5"- >- Disconnect- </Button>- )}+ <div className="flex items-center gap-2 shrink-0">+ {errorAction && (+ <Button+ variant="outline"+ size="sm"+ onClick={errorAction.onClick}+ className="shrink-0 text-xs h-7 px-2.5"+ >+ {errorAction.label}+ </Button>+ )}+ {onDisconnect && (+ <Button+ variant="destructive"+ size="sm"+ onClick={onDisconnect}+ className="shrink-0 text-xs h-7 px-2.5"+ >+ Disconnect+ </Button>+ )}+ </div></div></div>)}diff --cc src/agent/async-agent.tsindex 1490f09428,824da61779..8015b95eb9--- a/src/agent/async-agent.ts+++ b/src/agent/async-agent.ts@@@ -66,16 -71,15 +71,17 @@@ export class AsyncAgentawait this.agent.flushSession();// Normal text is delivered via message_end event; only handle errors hereif (result.error) {+ console.error(`[AsyncAgent] Agent run error: ${result.error}`);this.channel.send({ id: uuidv7(), content: `[error] ${result.error}` });- this.agent.emitMulticaEvent({ type: "agent_error", error: result.error });+ this.agent.emitError(result.error);}}).catch((err) => {const message = err instanceof Error ? err.message : String(err);+ console.error(`[AsyncAgent] Agent run exception: ${message}`);this.channel.send({ id: uuidv7(), content: `[error] ${message}` });- this.agent.emitMulticaEvent({ type: "agent_error", error: message });+ // Also emit through subscriber mechanism so IPC listeners receive the error+ this.agent.emitError(message);}).finally(() => {this.pendingWrites = Math.max(0, this.pendingWrites - 1);diff --cc src/channels/manager.tsindex 8762d6746c,0000000000..b0042cc115mode 100644,000000..100644--- a/src/channels/manager.ts+++ b/src/channels/manager.ts@@@ -1,503 -1,0 +1,503 @@@+/**+ * Channel Manager — bridges messaging channels to the Hub's agent.+ *+ * Design: One Hub, one Agent. Channels are just alternative input/output surfaces.+ * - Incoming: channel message → agent.write(text) (same as desktop/gateway)+ * - Outgoing: agent reply → check lastRoute → forward to originating channel+ *+ * Uses "last route" pattern: whoever sent the last message gets the reply.+ *+ * @see docs/channels/README.md — Channel system overview+ * @see docs/channels/media-handling.md — Media processing pipeline+ * @see docs/message-paths.md — All three message paths (Desktop / Web / Channel)+ */++import type { Hub } from "../hub/hub.js";+import type {+ ChannelPlugin,+ ChannelMessage,+ ChannelAccountState,+ DeliveryContext,+} from "./types.js";+import { listChannels } from "./registry.js";+import { loadChannelsConfig } from "./config.js";+import { MessageAggregator, DEFAULT_CHUNKER_CONFIG } from "../hub/message-aggregator.js";+import type { AsyncAgent } from "../agent/async-agent.js";+import { transcribeAudio } from "../media/transcribe.js";+import { describeImage } from "../media/describe-image.js";+import { describeVideo } from "../media/describe-video.js";+import { InboundDebouncer } from "./inbound-debouncer.js";++interface AccountHandle {+ channelId: string;+ accountId: string;+ abortController: AbortController;+ state: ChannelAccountState;+}++/** Tracks where the last message came from, so replies go back there. */+interface LastRoute {+ plugin: ChannelPlugin;+ deliveryCtx: DeliveryContext;+}++export class ChannelManager {+ private readonly hub: Hub;+ /** Running accounts keyed by "channelId:accountId" */+ private readonly accounts = new Map<string, AccountHandle>();+ /** Where the last channel message came from (reply target) */+ private lastRoute: LastRoute | null = null;+ /** Unsubscribe function for the agent subscriber */+ private agentUnsubscribe: (() => void) | null = null;+ /** Session ID of the currently subscribed agent (for stale detection) */+ private subscribedAgentId: string | null = null;+ /** Current aggregator for buffering streaming responses */+ private aggregator: MessageAggregator | null = null;+ /** Typing indicator interval (repeats every 5s to keep Telegram typing visible) */+ private typingTimer: ReturnType<typeof setInterval> | null = null;+ /**+ * Inbound message debouncer — batches rapid-fire messages from the same+ * conversation into a single agent.write() call.+ * Initialized lazily on first message; uses the current agent reference.+ */+ private debouncer: InboundDebouncer | null = null;++ constructor(hub: Hub) {+ this.hub = hub;+ }++ /** Start all configured channel accounts */+ async startAll(): Promise<void> {+ console.log("[Channels] Starting all channels...");+ const config = loadChannelsConfig();+ const plugins = listChannels();++ if (plugins.length === 0) {+ console.log("[Channels] No plugins registered");+ return;+ }++ for (const plugin of plugins) {+ const accountIds = plugin.config.listAccountIds(config);+ if (accountIds.length === 0) {+ console.log(`[Channels] Skipping ${plugin.id} (not configured)`);+ continue;+ }++ for (const accountId of accountIds) {+ const account = plugin.config.resolveAccount(config, accountId);+ if (!account || !plugin.config.isConfigured(account)) {+ console.log(`[Channels] Skipping ${plugin.id}:${accountId} (incomplete config)`);+ continue;+ }+ await this.startAccount(plugin.id, accountId, account);+ }+ }++ // Try to subscribe eagerly; if no agent yet, routeIncoming will retry lazily+ this.ensureSubscribed();+ }++ /**+ * Start a specific channel account.+ * Public so the desktop IPC layer can call it after saving config.+ */+ async startAccount(+ channelId: string,+ accountId: string,+ accountConfig: Record<string, unknown>,+ ): Promise<void> {+ const key = `${channelId}:${accountId}`;+ if (this.accounts.has(key)) {+ console.warn(`[Channels] ${key} is already running`);+ return;+ }++ const plugin = listChannels().find((p) => p.id === channelId);+ if (!plugin) {+ console.error(`[Channels] Plugin "${channelId}" not found`);+ return;+ }++ const abortController = new AbortController();+ const handle: AccountHandle = {+ channelId,+ accountId,+ abortController,+ state: { channelId, accountId, status: "starting" },+ };+ this.accounts.set(key, handle);++ console.log(`[Channels] Starting ${key}`);++ try {+ const startPromise = plugin.gateway.start(+ accountId,+ accountConfig,+ (message: ChannelMessage) => {+ this.routeIncoming(plugin, accountId, message);+ },+ abortController.signal,+ );++ await Promise.race([+ startPromise,+ new Promise<void>((resolve) => setTimeout(resolve, 3000)),+ ]);++ handle.state = { channelId, accountId, status: "running" };+ console.log(`[Channels] ${key} is running`);+ } catch (err) {+ const errorMsg = err instanceof Error ? err.message : String(err);+ handle.state = { channelId, accountId, status: "error", error: errorMsg };+ console.error(`[Channels] Failed to start ${key}: ${errorMsg}`);+ }+ }++ /** Get the Hub's current agent (the first active one) */+ private getHubAgent(): AsyncAgent | undefined {+ const agentIds = this.hub.listAgents();+ if (agentIds.length === 0) {+ console.warn("[Channels] No agent available in Hub");+ return undefined;+ }+ const agent = this.hub.getAgent(agentIds[0]!);+ return agent;+ }++ /**+ * Ensure we're subscribed to the current Hub agent for outbound routing.+ * Lazily called from routeIncoming — handles agent not yet available at+ * startup and re-subscribes if the agent has changed.+ */+ private ensureSubscribed(): void {+ const agent = this.getHubAgent();+ if (!agent) return;++ // Already subscribed to the current agent+ if (this.subscribedAgentId === agent.sessionId) return;++ // Unsubscribe from stale agent+ if (this.agentUnsubscribe) {+ console.log(`[Channels] Agent changed, re-subscribing (${this.subscribedAgentId} → ${agent.sessionId})`);+ this.agentUnsubscribe();+ }++ console.log(`[Channels] Subscribing to agent ${agent.sessionId} for outbound routing`);+ this.subscribedAgentId = agent.sessionId;++ this.agentUnsubscribe = agent.subscribe((event) => {+ // No active channel route — skip (reply goes to desktop/gateway only)+ if (!this.lastRoute) return;++ // Handle agent errors — notify the channel user+ if (event.type === "agent_error") {+ this.stopTyping();+ this.removeAckReaction();- const errorMsg = (event as { error?: string }).error ?? "Unknown error";++ const errorMsg = (event as { message?: string }).message ?? "Unknown error";+ console.error(`[Channels] Agent error: ${errorMsg}`);+ const route = this.lastRoute;+ if (route) {+ void route.plugin.outbound.sendText(route.deliveryCtx, `[Error] ${errorMsg}`).catch((err) => {+ console.error(`[Channels] Failed to send error to channel: ${err}`);+ });+ }+ return;+ }++ const maybeMessage = (event as { message?: { role?: string } }).message;+ const role = maybeMessage?.role;++ // Only forward assistant message events+ if (event.type === "message_start" || event.type === "message_update" || event.type === "message_end") {+ if (role !== "assistant") return;+ } else {+ // Non-message events (tool_execution etc.) — skip for channels+ return;+ }++ // Ensure aggregator exists for this response+ if (event.type === "message_start") {+ this.createAggregator();+ }++ if (this.aggregator) {+ this.aggregator.handleEvent(event);+ }++ // Clean up after response complete+ if (event.type === "message_end" && role === "assistant") {+ this.stopTyping();+ this.removeAckReaction();+ this.aggregator = null;+ }+ });+ }++ /** Create a fresh aggregator wired to the current lastRoute */+ private createAggregator(): void {+ const route = this.lastRoute;+ if (!route) return;++ const { plugin, deliveryCtx } = route;+ const chunkerConfig = plugin.chunkerConfig ?? DEFAULT_CHUNKER_CONFIG;++ this.aggregator = new MessageAggregator(+ chunkerConfig,+ async (block) => {+ try {+ console.log(`[Channels] Sending block ${block.index} (${block.text.length} chars${block.isFinal ? ", final" : ""}) → ${deliveryCtx.channel}:${deliveryCtx.conversationId}`);+ if (block.index === 0) {+ await plugin.outbound.replyText(deliveryCtx, block.text);+ } else {+ await plugin.outbound.sendText(deliveryCtx, block.text);+ }+ } catch (err) {+ console.error(`[Channels] Failed to send reply: ${err}`);+ }+ },+ () => {},+ );+ }++ /**+ * Incoming channel message → update lastRoute → forward to Hub's agent.+ */+ private routeIncoming(+ plugin: ChannelPlugin,+ accountId: string,+ message: ChannelMessage,+ ): void {+ const { conversationId, senderId, text, messageId } = message;+ console.log(+ `[Channels] Incoming: channel=${plugin.id} conv=${conversationId} sender=${senderId} text="${text.slice(0, 50)}${text.length > 50 ? "..." : ""}"`,+ );++ const agent = this.getHubAgent();+ if (!agent) {+ console.error("[Channels] No agent available, dropping message");+ return;+ }++ // Ensure we're subscribed to this agent (handles late startup / agent change)+ this.ensureSubscribed();++ // Update last route — replies will go back here+ this.lastRoute = {+ plugin,+ deliveryCtx: {+ channel: plugin.id,+ accountId,+ conversationId,+ replyToMessageId: messageId,+ },+ };+ console.log(`[Channels] lastRoute updated → ${plugin.id}:${conversationId}`);+ console.log(`[Channels] Forwarding to agent ${agent.sessionId}`);++ // Show typing indicator and ACK reaction while agent processes+ this.startTyping();+ this.addAckReaction();++ // Handle media messages (processed async, then fed through debouncer)+ if (message.media && plugin.downloadMedia) {+ void this.routeMedia(plugin, accountId, message, agent);+ } else {+ // Text messages go through debouncer to batch rapid-fire sends+ this.getDebouncer(agent).push(conversationId, text);+ }+ }++ /**+ * Download media file, process it (transcribe/describe), and forward+ * the resulting text through the debouncer to the agent.+ * Media results are also debounced so that a rapid "photo + text" combo+ * from the same conversation gets batched into one agent prompt.+ */+ private async routeMedia(+ plugin: ChannelPlugin,+ accountId: string,+ message: ChannelMessage,+ agent: AsyncAgent,+ ): Promise<void> {+ const media = message.media!;+ const debouncer = this.getDebouncer(agent);++ try {+ const filePath = await plugin.downloadMedia!(media.fileId, accountId);++ if (media.type === "image") {+ // Images: describe via Vision API before reaching agent+ const description = await describeImage(filePath);+ if (description) {+ const parts = ["[Image]", `Description: ${description}`];+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ } else {+ // No API key — fall back to file path+ const parts = ["[image message received]", `File: ${filePath}`];+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ }+ } else if (media.type === "audio") {+ // Audio: transcribe via Whisper API before reaching agent+ const transcript = await transcribeAudio(filePath);+ if (transcript) {+ const parts = ["[Voice Message]", `Transcript: ${transcript}`];+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ } else {+ // No API key configured — fall back to file path+ const parts = ["[audio message received]", `File: ${filePath}`];+ if (media.mimeType) parts.push(`Type: ${media.mimeType}`);+ if (media.duration) parts.push(`Duration: ${media.duration}s`);+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ }+ } else if (media.type === "video") {+ // Video: extract frame + describe via Vision API+ const description = await describeVideo(filePath);+ if (description) {+ const parts = ["[Video]", `Description: ${description}`];+ if (media.duration) parts.push(`Duration: ${media.duration}s`);+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ } else {+ // ffmpeg unavailable or no API key — fall back to file path+ const parts = ["[video message received]", `File: ${filePath}`];+ if (media.mimeType) parts.push(`Type: ${media.mimeType}`);+ if (media.duration) parts.push(`Duration: ${media.duration}s`);+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ }+ } else {+ // Document: tell agent the file path+ const parts: string[] = [];+ parts.push(`[document message received]`);+ parts.push(`File: ${filePath}`);+ if (media.mimeType) parts.push(`Type: ${media.mimeType}`);+ if (media.caption) parts.push(`Caption: ${media.caption}`);+ debouncer.push(message.conversationId, parts.join("\n"));+ }+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ console.error(`[Channels] Failed to process media: ${msg}`);+ debouncer.push(message.conversationId, message.text || `[Failed to process ${media.type}]`);+ }+ }++ /**+ * Get or create the inbound debouncer, wired to the given agent.+ * The debouncer batches rapid-fire messages by conversationId, then+ * calls agent.write() once with the combined text.+ */+ private getDebouncer(agent: AsyncAgent): InboundDebouncer {+ if (!this.debouncer) {+ this.debouncer = new InboundDebouncer(+ (_conversationId, combinedText) => {+ console.log(`[Channels] Debouncer flushing ${combinedText.length} chars to agent`);+ agent.write(combinedText);+ },+ );+ }+ return this.debouncer;+ }++ /** Add 👀 reaction to acknowledge message receipt */+ private addAckReaction(): void {+ const route = this.lastRoute;+ if (!route?.plugin.outbound.addReaction) return;+ void route.plugin.outbound.addReaction(route.deliveryCtx, "👀").catch(() => {});+ }++ /** Remove ACK reaction when processing completes */+ private removeAckReaction(): void {+ const route = this.lastRoute;+ if (!route?.plugin.outbound.removeReaction) return;+ void route.plugin.outbound.removeReaction(route.deliveryCtx).catch(() => {});+ }++ /** Start sending typing indicators (repeats every 5s until stopped) */+ private startTyping(): void {+ this.stopTyping();+ const route = this.lastRoute;+ if (!route?.plugin.outbound.sendTyping) return;++ const send = () => route.plugin.outbound.sendTyping!(route.deliveryCtx).catch(() => {});+ void send();+ this.typingTimer = setInterval(send, 5000);+ }++ /** Stop typing indicator interval */+ private stopTyping(): void {+ if (this.typingTimer) {+ clearInterval(this.typingTimer);+ this.typingTimer = null;+ }+ }++ /**+ * Stop a specific channel account.+ * Public so the desktop IPC layer can call it when removing config.+ * Cleans up typing timer, debouncer, aggregator, and lastRoute if they+ * belong to this account.+ */+ stopAccount(channelId: string, accountId: string): void {+ const key = `${channelId}:${accountId}`;+ const handle = this.accounts.get(key);+ if (!handle) return;++ // Clean up shared resources if they target this account+ if (this.lastRoute && this.lastRoute.plugin.id === channelId && this.lastRoute.deliveryCtx.accountId === accountId) {+ this.stopTyping();+ this.lastRoute = null;+ this.aggregator = null;+ }++ handle.abortController.abort();+ handle.state = { ...handle.state, status: "stopped" };+ this.accounts.delete(key);++ // Dispose debouncer if no accounts remain+ if (this.accounts.size === 0 && this.debouncer) {+ this.debouncer.dispose();+ this.debouncer = null;+ }++ console.log(`[Channels] Stopped ${key}`);+ }++ /** Stop all running channel accounts */+ stopAll(): void {+ console.log("[Channels] Stopping all channels...");+ this.stopTyping();+ this.debouncer?.dispose();+ this.debouncer = null;+ if (this.agentUnsubscribe) {+ this.agentUnsubscribe();+ this.agentUnsubscribe = null;+ }+ for (const [key, handle] of this.accounts) {+ handle.abortController.abort();+ handle.state = { ...handle.state, status: "stopped" };+ console.log(`[Channels] Stopped ${key}`);+ }+ this.accounts.clear();+ this.lastRoute = null;+ this.aggregator = null;+ }++ /** Clear the last route (e.g. when desktop user sends a message) */+ clearLastRoute(): void {+ if (this.lastRoute) {+ this.stopTyping();+ console.log("[Channels] lastRoute cleared (non-channel message received)");+ this.lastRoute = null;+ }+ }++ /** Get status of all accounts */+ listAccountStates(): ChannelAccountState[] {+ return Array.from(this.accounts.values()).map((h) => ({ ...h.state }));+ }+}