示例工程 61-chat-ui-streaming

61-chat-ui-streaming/app/shared/chat.ts

typescript · 4.2 KB

export type DiffLine = {
  kind: "add" | "del" | "ctx";
  text: string;
};

export type DiffView = {
  path: string;
  lines: DiffLine[];
};

export type ToolView = {
  name: string;
  args: Record<string, string>;
  status: "running" | "ok";
  result: string;
};

export type ChatMessage = {
  id: string;
  role: "user" | "assistant";
  text: string;
  streaming: boolean;
  attempt: number;
  tool: ToolView | null;
  diff: DiffView | null;
  error: string | null;
  at: number;
};

export type RunSummary = {
  id: string;
  prompt: string;
  attempt: number;
  deltas: number;
  chars: number;
  toolCalls: number;
  diffLines: number;
  done: boolean;
  cancelled: boolean;
  error: string | null;
  elapsedMs: number;
};

export type ChatSnapshot = {
  platform: string;
  electronVersion: string;
  nodeVersion: string;
  messages: ChatMessage[];
  running: boolean;
  lastRun: RunSummary | null;
  runs: RunSummary[];
  draft: string;
};

export type StreamHandlers = {
  onDelta: (text: string) => void;
  onTool: (tool: ToolView) => void;
  onDiff: (diff: DiffView) => void;
  onToolResult: (result: string) => void;
};

function abortError(): Error {
  const error = new Error("ABORTED");
  error.name = "AbortError";
  return error;
}

function sleep(ms: number, signal: AbortSignal): Promise<void> {
  return new Promise((resolve, reject) => {
    if (signal.aborted) {
      reject(abortError());
      return;
    }
    const timer = setTimeout(() => {
      signal.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    const onAbort = (): void => {
      clearTimeout(timer);
      reject(abortError());
    };
    signal.addEventListener("abort", onAbort, { once: true });
  });
}

const DELTAS_ONE = ["我会先更新", "配置文件,", "再说明改动。"];
const DELTAS_TWO = ["已写入 4 行,", "保留了原有导出。"];

const DIFF: DiffView = {
  path: "src/config.ts",
  lines: [
    { kind: "ctx", text: "export const mode = 'dev';" },
    { kind: "del", text: "export const retries = 1;" },
    { kind: "add", text: "export const retries = 3;" },
    { kind: "add", text: "export const timeoutMs = 5000;" },
  ],
};

export async function streamAssistant(options: {
  prompt: string;
  attempt: number;
  paceMs: number;
  signal: AbortSignal;
  handlers: StreamHandlers;
}): Promise<RunSummary> {
  const started = Date.now();
  const id = `run-${started.toString(36)}`;
  const pace = Math.min(300, Math.max(4, options.paceMs));
  let deltas = 0;
  let chars = 0;
  let toolCalls = 0;
  let diffLines = 0;
  let done = false;
  let cancelled = false;
  let error: string | null = null;

  try {
    for (const text of DELTAS_ONE) {
      if (options.signal.aborted) throw abortError();
      await sleep(pace, options.signal);
      options.handlers.onDelta(text);
      deltas += 1;
      chars += text.length;
    }

    if (options.signal.aborted) throw abortError();
    await sleep(pace, options.signal);
    toolCalls += 1;
    options.handlers.onTool({
      name: "write_file",
      args: { path: DIFF.path, content: "+2 -1" },
      status: "running",
      result: "",
    });

    if (options.signal.aborted) throw abortError();
    await sleep(pace, options.signal);
    diffLines = DIFF.lines.length;
    options.handlers.onDiff(DIFF);

    if (options.signal.aborted) throw abortError();
    await sleep(pace, options.signal);
    options.handlers.onToolResult("wrote src/config.ts (+2 -1)");

    for (const text of DELTAS_TWO) {
      if (options.signal.aborted) throw abortError();
      await sleep(pace, options.signal);
      options.handlers.onDelta(text);
      deltas += 1;
      chars += text.length;
    }

    done = true;
  } catch (caught) {
    if (options.signal.aborted) {
      cancelled = true;
    } else {
      error = caught instanceof Error ? caught.message : String(caught);
    }
  }

  return {
    id,
    prompt: options.prompt,
    attempt: options.attempt,
    deltas,
    chars,
    toolCalls,
    diffLines,
    done,
    cancelled,
    error,
    elapsedMs: Date.now() - started,
  };
}

export function diffSummary(diff: DiffView): string {
  const added = diff.lines.filter((line) => line.kind === "add").length;
  const removed = diff.lines.filter((line) => line.kind === "del").length;
  return `${diff.path} +${added} -${removed}`;
}