Files
Netcatty/domain/aiSessionFork.ts
T
0ed481c397 feat(ai-chat): fork a conversation from a completed response (#3604)
* fix(#3600): automated AI fix

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix: address Codex review on PR #3604

* fix(ai): narrow chat forks to independent transcript copies

* test(ai): keep fork render check correctly typed

* fix(ai): remove forked output arguments and support keyboard access

* fix(ai): guard signed fork reasoning and scan eligibility once

* fix(ai): remove bare source output references from fork text

* fix(ai): sanitize fork attachment previews without changing data

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-10-15 14:38:53 +08:00

277 lines
10 KiB
TypeScript

import type { ChatMessageAttachment } from '../infrastructure/ai/types';
import type { ProviderContinuation } from '../infrastructure/ai/providerContinuation';
/**
* Pure planning logic for "Fork from here": copy an AI chat session up to a
* completed assistant response into a new session, leaving the original
* conversation untouched in history.
*
* Refusals (per the feature contract):
* - only completed assistant-response turn boundaries fork — streaming, failed,
* cancelled, or in-progress turns are rejected,
* - every tool call in the retained prefix must have a paired result and
* vice versa (no dangling calls or results on the branch),
* - a stored compaction summary that would cover messages discarded by the
* branch is refused (the summary must stay accurate for the fork),
* - incomplete-turn state (status text, pending approvals) is stripped while
* the per-message provider replay metadata is preserved, so the fresh
* provider thread replays the retained history.
*/
export type ForkRefusalReason =
| 'message-not-found'
| 'not-assistant'
| 'not-completed'
| 'dangling-tool-call'
| 'dangling-tool-result'
| 'compaction-covers-discarded'
| 'source-output-reasoning';
/** A message type that carries the fork-relevant subset (e.g. ChatMessage). */
export type ForkMessageLike = {
id: string;
role: 'user' | 'assistant' | 'system' | 'tool';
content: string;
thinking?: string;
providerContinuation?: ProviderContinuation;
attachments?: ReadonlyArray<ChatMessageAttachment>;
images?: ReadonlyArray<ChatMessageAttachment>;
toolCalls?: ReadonlyArray<{ id: string; name?: string; arguments?: Record<string, unknown> }>;
toolResults?: ReadonlyArray<{ toolCallId: string; content?: string; isError?: boolean }>;
errorInfo?: unknown;
statusText?: string;
pendingApproval?: unknown;
executionStatus?: string;
};
/** Structural subset of ChatMessage the fork planner needs. */
export type ForkMessage = ForkMessageLike & { timestamp?: number };
export type ForkPlan<M extends ForkMessageLike = ForkMessage> =
| {
ok: true;
boundaryIndex: number;
title: string;
messages: M[];
contextCompaction?: ForkContextCompaction;
}
| { ok: false; reason: ForkRefusalReason };
export type ForkContextCompaction = {
summary: string;
compactedMessageCount: number;
};
const INCOMPLETE_EXECUTION_STATUSES = new Set([
'pending',
'running',
'failed',
'cancelled',
]);
function isCompletedResponse(message: ForkMessageLike): boolean {
return message.role === 'assistant'
&& message.errorInfo == null
&& message.statusText == null
&& message.pendingApproval == null
&& !INCOMPLETE_EXECUTION_STATUSES.has(message.executionStatus ?? '');
}
function hasSourceOutputReasoning(message: ForkMessageLike): boolean {
return (message.providerContinuation?.reasoningParts ?? []).some(
part => /\btool-output-[A-Za-z0-9-]+/.test(part.text),
);
}
/** Eligibility only: never copy/sanitize transcript content while rendering. */
export function getForkableMessageIds(source: {
messages: readonly ForkMessageLike[];
contextCompaction?: ForkContextCompaction;
}): Set<string> {
const ids = new Set<string>();
const pending = new Map<string, number>();
let pendingCount = 0;
let orphanResult = false;
let sourceOutputReasoning = false;
for (const [index, message] of source.messages.entries()) {
sourceOutputReasoning ||= hasSourceOutputReasoning(message);
for (const call of message.toolCalls ?? []) {
if (!call.id) continue;
pending.set(call.id, (pending.get(call.id) ?? 0) + 1);
pendingCount += 1;
}
for (const result of message.toolResults ?? []) {
if (!result.toolCallId) continue;
const count = pending.get(result.toolCallId) ?? 0;
if (count === 0) orphanResult = true;
else {
pending.set(result.toolCallId, count - 1);
pendingCount -= 1;
}
}
if (isCompletedResponse(message) && pendingCount === 0
&& !orphanResult && !sourceOutputReasoning
&& (source.contextCompaction?.compactedMessageCount ?? 0) <= index + 1) {
ids.add(message.id);
}
}
return ids;
}
/**
* Validate that every tool call in the retained prefix is paired with a
* result and vice versa. Providers may reuse a tool-call id across turns, so
* each result is consumed by the nearest preceding unresolved call with the
* same id (same pairing rule as buildHistoricalToolReplayMaps): a result with
* no pending call before it is dangling, and so is a call still pending after
* the walk.
*/
function validateToolCallResultPairing(
messages: readonly ForkMessageLike[],
): 'dangling-tool-call' | 'dangling-tool-result' | null {
const pendingCallCounts = new Map<string, number>();
for (const message of messages) {
for (const toolCall of message.toolCalls ?? []) {
if (!toolCall?.id) continue;
pendingCallCounts.set(toolCall.id, (pendingCallCounts.get(toolCall.id) ?? 0) + 1);
}
for (const toolResult of message.toolResults ?? []) {
const id = toolResult?.toolCallId;
if (!id) continue;
const pendingCount = pendingCallCounts.get(id) ?? 0;
if (pendingCount === 0) return 'dangling-tool-result';
pendingCallCounts.set(id, pendingCount - 1);
}
}
for (const pendingCount of pendingCallCounts.values()) {
if (pendingCount > 0) return 'dangling-tool-call';
}
return null;
}
/**
* Strip incomplete-turn state so the branch starts clean; per-message provider
* continuation metadata (Responses reasoning items, OpenAI Chat assistant
* fields, tool-call wire options) is preserved because the fork's fresh
* provider thread replays the retained history through it and safely discards
* exchanges whose metadata no longer matches the active provider.
*/
/** Keep the preview but remove unusable source-session output references. */
function stripSourceOutputHandles(value: string): string {
return value
.replace(/\bhandleId=tool-output-[A-Za-z0-9-]+/g, '[saved output remains in the original chat]')
.replace(/"handleId"\s*:\s*"tool-output-[A-Za-z0-9-]+"/g, '"handleId":null,"note":"Saved output remains in the original chat"')
.replace(/\btool-output-[A-Za-z0-9-]+/g, '[saved output remains in the original chat]');
}
function stripAttachmentPreview<A extends { previewText?: string }>(attachment: A): A {
return attachment.previewText
? { ...attachment, previewText: stripSourceOutputHandles(attachment.previewText) }
: attachment;
}
export function stripMessageContinuationState<M extends ForkMessageLike>(message: M): M {
const next = {
...message,
content: stripSourceOutputHandles(message.content),
...(message.attachments ? { attachments: message.attachments.map(stripAttachmentPreview) } : {}),
...(message.images ? { images: message.images.map(stripAttachmentPreview) } : {}),
...(message.thinking ? { thinking: stripSourceOutputHandles(message.thinking) } : {}),
...(message.toolCalls ? {
toolCalls: message.toolCalls.map(call => {
if (call.name !== 'tool_output_read'
|| typeof call.arguments?.handleId !== 'string'
|| !call.arguments.handleId.startsWith('tool-output-')) return call;
const args = { ...call.arguments };
delete args.handleId;
return { ...call, arguments: args };
}),
} : {}),
...(message.toolResults ? {
toolResults: message.toolResults.map(result => ({
...result,
...(result.content ? { content: stripSourceOutputHandles(result.content) } : {}),
})),
} : {}),
};
delete next.statusText;
delete next.pendingApproval;
return next;
}
export function buildForkTitle(title: string): string {
const base = (title ?? '').trim() || 'New Chat';
return base.endsWith('(fork)') ? base : `${base} (fork)`;
}
/** Structural subset of AISession the fork planner needs. */
export type ForkSourceSession<M extends ForkMessageLike = ForkMessage> = {
title: string;
messages: readonly M[];
contextCompaction?: ForkContextCompaction;
};
/**
* Plan a fork at `messageId`. Returns a refusal reason when the boundary is
* not a safe completed turn, or the retained message list (trimmed of
* incomplete-turn state, keeping provider replay metadata) plus the
* carried-over compaction (when still accurate).
*/
export function planSessionFork<M extends ForkMessageLike>(
source: ForkSourceSession<M>,
messageId: string,
): ForkPlan<M> {
const boundaryIndex = source.messages.findIndex(
(message) => message.id === messageId,
);
if (boundaryIndex === -1) return { ok: false, reason: 'message-not-found' };
const boundary = source.messages[boundaryIndex];
if (boundary.role !== 'assistant') return { ok: false, reason: 'not-assistant' };
if (!isCompletedResponse(boundary)) return { ok: false, reason: 'not-completed' };
const retained = source.messages.slice(0, boundaryIndex + 1);
// Provider reasoning can be signed: replacing text or dropping only that
// block can invalidate its tool exchange. Refuse this cut without changing
// the source metadata rather than leaking an unusable source-only handle.
if (retained.some(hasSourceOutputReasoning)) {
return { ok: false, reason: 'source-output-reasoning' };
}
const pairingRefusal = validateToolCallResultPairing(retained);
if (pairingRefusal) return { ok: false, reason: pairingRefusal };
// A stored compaction summary covers the earliest `compactedMessageCount`
// persisted messages. The summary must never cover messages discarded by
// the branch, so refuse when its coverage would exceed the retained prefix.
const compaction = source.contextCompaction;
let nextCompaction: ForkContextCompaction | undefined;
if (compaction) {
if (compaction.compactedMessageCount > retained.length) {
return { ok: false, reason: 'compaction-covers-discarded' };
}
nextCompaction = {
summary: stripSourceOutputHandles(compaction.summary),
compactedMessageCount: compaction.compactedMessageCount,
};
}
return {
ok: true,
boundaryIndex,
title: buildForkTitle(source.title),
messages: retained.map(stripMessageContinuationState),
...(nextCompaction ? { contextCompaction: nextCompaction } : {}),
} as ForkPlan<M>;
}
export function canForkFromMessage(
source: {
messages: readonly ForkMessageLike[];
contextCompaction?: ForkContextCompaction;
},
messageId: string,
): boolean {
return getForkableMessageIds(source).has(messageId);
}