mirror of
https://github.com/wu736139669/hapi.git
synced 2026-08-07 06:52:28 +00:00
feat: message-level conversation fork and rewind (#1263)
* feat: add message-level conversation fork and rewind Expose native Codex/Grok/Claude history controls through hub REST+RPC and web ConfirmDialog actions, without file rewind or composed forks. Also reconcile the duplicate hub V14→V15 migration so typecheck can pass. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: hydrate fork transcript and consume Claude --fork-session Forked HAPI children now copy the source transcript prefix so navigation is not a blank thread, and Claude drops --fork-session after the first launch so relaunches do not branch again. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: harden fork/rewind concurrency and durable history points Skip pending scheduled rows when hydrating fork transcripts, serialize fork/rewind per session, and persist conversation history points/indexes across existing-session bootstrap and Grok relaunches. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close remaining fork/rewind races and UI anchoring Block sends and scheduled maturation while history actions run, order fork prefixes by invocation time, inherit history locators into children, and only offer Fork current on the live tail boundary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: address remaining fork/rewind bot findings Materialize Claude --fork-session before the first child prompt, validate HAPI history boundaries before native RPC, expose forkCurrent on a latest user boundary, fully demote unsupported conversationHistory capabilities, and fix the truncate test setup order. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: align fork-current ids and Claude fork bootstrap Compare the latest fork boundary in assistant-ui threadMessageId space, spawn Claude forks with the persisted session mode, and preserve forkedFrom across existing-session bootstrap. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close fork/rewind consistency holes at the contract layer Hold the source history lock until Claude child binds a distinct native id, persist Codex localId→turnId locators, and mark/block diverged sessions when native rewind outruns HAPI truncate. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: use Codex stable lastTurnId for historical fork Map HAPI's exclusive boundary to the previous turn's inclusive lastTurnId so native fork context matches the hydrated transcript. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: require exact Grok native resume for fork children Reject newSession fallback when forkedFrom is set, and keep the hub history lock until the child binds the forked grokSessionId. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: kill active fork children before failed-fork cleanup Bind/readiness failures can leave the child process running; deleteSession rejects active rows, so terminate first then remove the HAPI session. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close remaining fork lock, hydrate, and todos gaps Reject mode switches during history actions, batch-copy fork transcripts in one SQLite transaction, and rebuild todos after fork hydrate / rewind truncate. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: allow Codex historical fork before the first turn Use experimental beforeTurnId when there is no previous turn for the stable inclusive lastTurnId boundary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: mark Grok history busy immediately after dequeue Hub idle checks clear once messages-consumed fires; hold the busy flag across permission sync and rewind-points lookup before prompt starts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: encode copied conversation history content * fix(web): hide local conversation history actions * style(codex): remove trailing whitespace * fix(fork): preserve children when cleanup is unconfirmed * fix(history): confirm cleanup and guard rewind divergence * fix(history): probe capabilities before advertising --------- Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -468,6 +468,26 @@ export class ApiClient {
|
||||
})
|
||||
}
|
||||
|
||||
async forkConversation(sessionId: string, messageLocalId?: string): Promise<{ sessionId: string }> {
|
||||
return await this.request<{ sessionId: string }>(
|
||||
`/api/sessions/${encodeURIComponent(sessionId)}/fork`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(messageLocalId ? { messageLocalId } : {})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async rewindConversation(sessionId: string, messageLocalId: string): Promise<{ success: true }> {
|
||||
return await this.request<{ success: true }>(
|
||||
`/api/sessions/${encodeURIComponent(sessionId)}/rewind`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ messageLocalId })
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async archiveSession(sessionId: string): Promise<void> {
|
||||
await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/archive`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -421,6 +421,10 @@ export function HappyThread(props: {
|
||||
disabled: boolean
|
||||
onRefresh: () => void
|
||||
onRetryMessage?: (localId: string) => void
|
||||
historyActionPending?: boolean
|
||||
onForkConversation?: (messageLocalId?: string) => Promise<void>
|
||||
onRewindConversation?: (messageLocalId: string) => Promise<void>
|
||||
isLatestCompletedBoundary?: (messageId: string) => boolean
|
||||
onViewModeChange: (mode: 'tail' | 'history') => void
|
||||
isSyncingTail: boolean
|
||||
messagesWarning: string | null
|
||||
@@ -1439,6 +1443,10 @@ export function HappyThread(props: {
|
||||
disabled: props.disabled,
|
||||
onRefresh: props.onRefresh,
|
||||
onRetryMessage: props.onRetryMessage,
|
||||
historyActionPending: props.historyActionPending,
|
||||
onForkConversation: props.onForkConversation,
|
||||
onRewindConversation: props.onRewindConversation,
|
||||
isLatestCompletedBoundary: props.isLatestCompletedBoundary,
|
||||
onShareTurn: handleShareTurn,
|
||||
hasMoreMessages: props.hasMoreMessages,
|
||||
isSyncingTail: props.isSyncingTail,
|
||||
|
||||
@@ -14,6 +14,10 @@ export type HappyChatContextValue = {
|
||||
disabled: boolean
|
||||
onRefresh: () => void
|
||||
onRetryMessage?: (localId: string) => void
|
||||
historyActionPending?: boolean
|
||||
onForkConversation?: (messageLocalId?: string) => Promise<void>
|
||||
onRewindConversation?: (messageLocalId: string) => Promise<void>
|
||||
isLatestCompletedBoundary?: (messageId: string) => boolean
|
||||
onShareTurn?: (
|
||||
messageElement: HTMLElement | string | null,
|
||||
clientY?: number,
|
||||
|
||||
@@ -8,6 +8,7 @@ import { getAssistantCopyText } from '@/components/AssistantChat/messages/assist
|
||||
import { getConversationMessageAnchorId } from '@/chat/outline'
|
||||
import { CodexReviewCard } from '@/components/AssistantChat/messages/CodexReviewCard'
|
||||
import { MessageActions } from '@/components/AssistantChat/messages/MessageActions'
|
||||
import { useHappyChatContext } from '@/components/AssistantChat/context'
|
||||
|
||||
const TOOL_COMPONENTS = {
|
||||
Fallback: HappyToolMessage
|
||||
@@ -21,6 +22,7 @@ const MESSAGE_PART_COMPONENTS = {
|
||||
} as const
|
||||
|
||||
export function HappyAssistantMessage() {
|
||||
const ctx = useHappyChatContext()
|
||||
const messageId = useAuiState((s) => s.message.id)
|
||||
const elementId = getConversationMessageAnchorId(messageId)
|
||||
const isCliOutput = useAuiState((s) => {
|
||||
@@ -53,6 +55,14 @@ export function HappyAssistantMessage() {
|
||||
|
||||
const metadata = { durationMs, usage, model: messageModel ?? null, turnCount }
|
||||
|
||||
const history = ctx.metadata?.capabilities?.conversationHistory
|
||||
const showForkCurrent = Boolean(
|
||||
history?.forkCurrent
|
||||
&& ctx.isLatestCompletedBoundary?.(messageId)
|
||||
&& !ctx.disabled
|
||||
&& ctx.onForkConversation
|
||||
)
|
||||
|
||||
const rootClass = toolOnly
|
||||
? 'py-1 min-w-0 max-w-full overflow-x-hidden'
|
||||
: 'px-1 min-w-0 max-w-full overflow-x-hidden'
|
||||
@@ -68,7 +78,15 @@ export function HappyAssistantMessage() {
|
||||
: codexReview
|
||||
? <CodexReviewCard review={codexReview} />
|
||||
: <MessagePrimitive.Content components={MESSAGE_PART_COMPONENTS} />}
|
||||
<MessageActions align="start" copyText={copyText || undefined} metadata={metadata} messageElementId={elementId} />
|
||||
<MessageActions
|
||||
align="start"
|
||||
copyText={copyText || undefined}
|
||||
metadata={metadata}
|
||||
messageElementId={elementId}
|
||||
showFork={showForkCurrent}
|
||||
historyActionPending={ctx.historyActionPending}
|
||||
onFork={showForkCurrent ? () => ctx.onForkConversation!() : undefined}
|
||||
/>
|
||||
</MessagePrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,11 +7,28 @@ import { MessageActions } from './MessageActions'
|
||||
const copy = vi.fn()
|
||||
|
||||
vi.mock('@assistant-ui/react', () => ({
|
||||
useAuiState: (selector: (state: { message: { createdAt: Date } }) => unknown) => selector({
|
||||
message: { createdAt: new Date(2026, 6, 12, 10, 30) }
|
||||
useAuiState: (selector: (state: { message: { createdAt: Date }; thread: { isRunning: boolean } }) => unknown) => selector({
|
||||
message: { createdAt: new Date(2026, 6, 12, 10, 30) },
|
||||
thread: { isRunning: false }
|
||||
})
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/ConfirmDialog', () => ({
|
||||
ConfirmDialog: (props: {
|
||||
isOpen: boolean
|
||||
title: string
|
||||
confirmLabel: string
|
||||
onConfirm: () => Promise<void>
|
||||
onClose: () => void
|
||||
}) => props.isOpen ? (
|
||||
<div>
|
||||
<div>{props.title}</div>
|
||||
<button type="button" onClick={() => void props.onConfirm()}>{props.confirmLabel}</button>
|
||||
<button type="button" onClick={props.onClose}>Cancel</button>
|
||||
</div>
|
||||
) : null
|
||||
}))
|
||||
|
||||
vi.mock('@radix-ui/react-popover', () => ({
|
||||
Root: ({ children }: PropsWithChildren) => <>{children}</>,
|
||||
Trigger: ({ children }: PropsWithChildren) => <>{children}</>,
|
||||
@@ -116,4 +133,42 @@ describe('MessageActions', () => {
|
||||
expect(row).not.toBeNull()
|
||||
expect(row!.className.split(' ')).not.toContain('happy-message-actions-desktop-only-row')
|
||||
})
|
||||
|
||||
it('hides Fork and Rewind when capabilities are off', () => {
|
||||
renderActions({ align: 'end', copyText: 'body' })
|
||||
expect(screen.queryByRole('button', { name: 'Fork' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Rewind' })).toBeNull()
|
||||
})
|
||||
|
||||
it('shows Fork confirm dialog and calls onFork only after confirm', async () => {
|
||||
const onFork = vi.fn(async () => {})
|
||||
renderActions({ align: 'start', copyText: 'body', showFork: true, onFork })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Fork' }))
|
||||
expect(onFork).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('Fork conversation')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(onFork).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Fork' }))
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Fork' }).at(-1)!)
|
||||
expect(onFork).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows Rewind destructive confirm and calls onRewind only after confirm', async () => {
|
||||
const onRewind = vi.fn(async () => {})
|
||||
renderActions({ align: 'end', copyText: 'body', showRewind: true, onRewind })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rewind' }))
|
||||
expect(onRewind).not.toHaveBeenCalled()
|
||||
expect(screen.getByText('Rewind conversation')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(onRewind).not.toHaveBeenCalled()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rewind' }))
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Rewind' }).at(-1)!)
|
||||
expect(onRewind).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Popover from '@radix-ui/react-popover'
|
||||
import { useState } from 'react'
|
||||
import { useAuiState } from '@assistant-ui/react'
|
||||
import { CheckIcon, CopyIcon, InfoIcon } from '@/components/icons'
|
||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard'
|
||||
@@ -7,20 +8,47 @@ import { MessageMetadata, buildMessageMetadataLabels, type MessageMetadataProps
|
||||
import { MessageTimestamp } from './MessageTimestamp'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { ShareTurnButton } from './ShareTurnButton'
|
||||
import { ConfirmDialog } from '@/components/ui/ConfirmDialog'
|
||||
|
||||
export type MessageHistoryAction = {
|
||||
kind: 'forkCurrent' | 'forkAtMessage' | 'rewind'
|
||||
messageLocalId?: string
|
||||
}
|
||||
|
||||
type MessageActionsProps = {
|
||||
align: 'start' | 'end'
|
||||
copyText?: string
|
||||
metadata?: Omit<MessageMetadataProps, 'className'>
|
||||
messageElementId?: string
|
||||
showFork?: boolean
|
||||
showRewind?: boolean
|
||||
historyActionPending?: boolean
|
||||
onFork?: () => Promise<void>
|
||||
onRewind?: () => Promise<void>
|
||||
}
|
||||
|
||||
export function MessageActions({ align, copyText, metadata, messageElementId }: MessageActionsProps) {
|
||||
export function MessageActions({
|
||||
align,
|
||||
copyText,
|
||||
metadata,
|
||||
messageElementId,
|
||||
showFork = false,
|
||||
showRewind = false,
|
||||
historyActionPending = false,
|
||||
onFork,
|
||||
onRewind
|
||||
}: MessageActionsProps) {
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
const { t } = useTranslation()
|
||||
const threadIsRunning = useAuiState(({ thread }) => thread?.isRunning ?? false)
|
||||
const canCopy = Boolean(copyText)
|
||||
const hasMetadata = metadata ? buildMessageMetadataLabels(metadata).length > 0 : false
|
||||
const [forkOpen, setForkOpen] = useState(false)
|
||||
const [rewindOpen, setRewindOpen] = useState(false)
|
||||
const [forkPending, setForkPending] = useState(false)
|
||||
const [rewindPending, setRewindPending] = useState(false)
|
||||
const actionsLocked = historyActionPending || forkPending || rewindPending || threadIsRunning
|
||||
|
||||
const shareButton = messageElementId && !threadIsRunning ? (
|
||||
<ShareTurnButton
|
||||
messageElementId={messageElementId}
|
||||
@@ -29,31 +57,108 @@ export function MessageActions({ align, copyText, metadata, messageElementId }:
|
||||
/>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'happy-message-actions mt-1 flex h-5 items-center gap-1',
|
||||
align === 'end' ? 'justify-end' : 'justify-start'
|
||||
)}
|
||||
>
|
||||
{align === 'end' ? <DesktopTimestamp /> : null}
|
||||
{align === 'end' && hasMetadata && metadata ? <MessageInfoPopover metadata={metadata} /> : null}
|
||||
{align === 'end' ? shareButton : null}
|
||||
{canCopy ? (
|
||||
const historyButtons = (
|
||||
<>
|
||||
{showFork && onFork ? (
|
||||
<button
|
||||
type="button"
|
||||
title={copied ? t('message.copied') : t('message.copy')}
|
||||
aria-label={copied ? t('message.copied') : t('message.copy')}
|
||||
className="flex h-5 w-5 items-center justify-center rounded text-[var(--app-hint)] transition-colors hover:bg-[var(--app-subtle-bg)] hover:text-[var(--app-fg)]"
|
||||
onClick={() => copy(copyText!)}
|
||||
title={t('message.fork')}
|
||||
aria-label={t('message.fork')}
|
||||
disabled={actionsLocked}
|
||||
className="flex h-5 items-center rounded px-1 text-[11px] text-[var(--app-hint)] transition-colors hover:bg-[var(--app-subtle-bg)] hover:text-[var(--app-fg)] disabled:opacity-40"
|
||||
onClick={() => setForkOpen(true)}
|
||||
>
|
||||
{copied ? <CheckIcon className="h-3.5 w-3.5 text-green-500" /> : <CopyIcon className="h-3.5 w-3.5" />}
|
||||
{t('message.fork')}
|
||||
</button>
|
||||
) : null}
|
||||
{align === 'start' ? shareButton : null}
|
||||
{align === 'start' && hasMetadata && metadata ? <MessageInfoPopover metadata={metadata} /> : null}
|
||||
{align === 'start' ? <DesktopTimestamp /> : null}
|
||||
</div>
|
||||
{showRewind && onRewind ? (
|
||||
<button
|
||||
type="button"
|
||||
title={t('message.rewind')}
|
||||
aria-label={t('message.rewind')}
|
||||
disabled={actionsLocked}
|
||||
className="flex h-5 items-center rounded px-1 text-[11px] text-[var(--app-hint)] transition-colors hover:bg-[var(--app-subtle-bg)] hover:text-[var(--app-fg)] disabled:opacity-40"
|
||||
onClick={() => setRewindOpen(true)}
|
||||
>
|
||||
{t('message.rewind')}
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
'happy-message-actions mt-1 flex h-5 items-center gap-1',
|
||||
align === 'end' ? 'justify-end' : 'justify-start'
|
||||
)}
|
||||
>
|
||||
{align === 'end' ? <DesktopTimestamp /> : null}
|
||||
{align === 'end' && hasMetadata && metadata ? <MessageInfoPopover metadata={metadata} /> : null}
|
||||
{align === 'end' ? shareButton : null}
|
||||
{canCopy ? (
|
||||
<button
|
||||
type="button"
|
||||
title={copied ? t('message.copied') : t('message.copy')}
|
||||
aria-label={copied ? t('message.copied') : t('message.copy')}
|
||||
className="flex h-5 w-5 items-center justify-center rounded text-[var(--app-hint)] transition-colors hover:bg-[var(--app-subtle-bg)] hover:text-[var(--app-fg)]"
|
||||
onClick={() => copy(copyText!)}
|
||||
>
|
||||
{copied ? <CheckIcon className="h-3.5 w-3.5 text-green-500" /> : <CopyIcon className="h-3.5 w-3.5" />}
|
||||
</button>
|
||||
) : null}
|
||||
{historyButtons}
|
||||
{align === 'start' ? shareButton : null}
|
||||
{align === 'start' && hasMetadata && metadata ? <MessageInfoPopover metadata={metadata} /> : null}
|
||||
{align === 'start' ? <DesktopTimestamp /> : null}
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={forkOpen}
|
||||
onClose={() => {
|
||||
if (!forkPending) setForkOpen(false)
|
||||
}}
|
||||
title={t('message.fork.confirmTitle')}
|
||||
description={t('message.fork.confirmDescription')}
|
||||
confirmLabel={t('message.fork')}
|
||||
confirmingLabel={t('message.fork.confirming')}
|
||||
isPending={forkPending}
|
||||
onConfirm={async () => {
|
||||
if (!onFork) return
|
||||
setForkPending(true)
|
||||
try {
|
||||
await onFork()
|
||||
setForkOpen(false)
|
||||
} finally {
|
||||
setForkPending(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={rewindOpen}
|
||||
onClose={() => {
|
||||
if (!rewindPending) setRewindOpen(false)
|
||||
}}
|
||||
title={t('message.rewind.confirmTitle')}
|
||||
description={t('message.rewind.confirmDescription')}
|
||||
confirmLabel={t('message.rewind')}
|
||||
confirmingLabel={t('message.rewind.confirming')}
|
||||
isPending={rewindPending}
|
||||
destructive
|
||||
onConfirm={async () => {
|
||||
if (!onRewind) return
|
||||
setRewindPending(true)
|
||||
try {
|
||||
await onRewind()
|
||||
setRewindOpen(false)
|
||||
} finally {
|
||||
setRewindPending(false)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,32 @@ export function HappyUserMessage() {
|
||||
const onRetry = canRetry ? () => ctx.onRetryMessage!(localId) : undefined
|
||||
const showStatus = shouldShowMessageStatus(status)
|
||||
|
||||
const history = ctx.metadata?.capabilities?.conversationHistory
|
||||
const hasNativePoint = typeof localId === 'string'
|
||||
&& localId.length > 0
|
||||
&& ctx.metadata?.conversationHistoryPoints?.[localId] === true
|
||||
const isLatestBoundary = ctx.isLatestCompletedBoundary?.(messageId) === true
|
||||
const showCurrentFork = Boolean(
|
||||
history?.forkCurrent
|
||||
&& isLatestBoundary
|
||||
&& !ctx.disabled
|
||||
&& ctx.onForkConversation
|
||||
)
|
||||
const showHistoricalFork = Boolean(
|
||||
history?.forkAtMessage
|
||||
&& hasNativePoint
|
||||
&& !isLatestBoundary
|
||||
&& !ctx.disabled
|
||||
&& ctx.onForkConversation
|
||||
)
|
||||
const showFork = showCurrentFork || showHistoricalFork
|
||||
const showRewind = Boolean(
|
||||
history?.rewindToMessage
|
||||
&& hasNativePoint
|
||||
&& !ctx.disabled
|
||||
&& ctx.onRewindConversation
|
||||
)
|
||||
|
||||
if (isCliOutput) {
|
||||
return (
|
||||
<MessagePrimitive.Root
|
||||
@@ -83,7 +109,22 @@ export function HappyUserMessage() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<MessageActions align="end" copyText={hasText ? text : undefined} messageElementId={elementId} />
|
||||
<MessageActions
|
||||
align="end"
|
||||
copyText={hasText ? text : undefined}
|
||||
messageElementId={elementId}
|
||||
showFork={showFork}
|
||||
showRewind={showRewind}
|
||||
historyActionPending={ctx.historyActionPending}
|
||||
onFork={showCurrentFork
|
||||
? () => ctx.onForkConversation!()
|
||||
: showHistoricalFork && localId
|
||||
? () => ctx.onForkConversation!(localId)
|
||||
: undefined}
|
||||
onRewind={showRewind && localId
|
||||
? () => ctx.onRewindConversation!(localId)
|
||||
: undefined}
|
||||
/>
|
||||
</MessagePrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import { normalizeDecryptedMessage } from '@/chat/normalize'
|
||||
import { reduceChatBlocks } from '@/chat/reducer'
|
||||
import { reconcileChatBlocks } from '@/chat/reconcile'
|
||||
import { buildConversationOutline } from '@/chat/outline'
|
||||
import { buildVisibleChatBlocks, isToolGroupBlock, type ToolGroupBlock } from '@/chat/toolGroups'
|
||||
import { buildVisibleChatBlocks, isToolGroupBlock, visibleBlockRole, type ToolGroupBlock } from '@/chat/toolGroups'
|
||||
import { useUnseenBlockCount } from '@/hooks/useUnseenBlockCount'
|
||||
import { isQueuedForInvocation } from '@/lib/messages'
|
||||
import { inactiveSessionCanResume } from '@/lib/sessionResume'
|
||||
@@ -42,7 +42,7 @@ import { classifySessionAttention, getSessionAttentionLabelKey } from '@/lib/ses
|
||||
import { getSessionLastSeenAt } from '@/lib/sessionLastSeen'
|
||||
import { formatRelativeTime } from '@/lib/relativeTime'
|
||||
import { ScratchlistMigrationBanner } from '@/components/AssistantChat/ScratchlistMigrationBanner'
|
||||
import { useHappyRuntime } from '@/lib/assistant-runtime'
|
||||
import { assignThreadMessageIds, useHappyRuntime } from '@/lib/assistant-runtime'
|
||||
import type { OlderLoadOutcome } from '@/lib/message-window-store'
|
||||
import { createAttachmentAdapter } from '@/lib/attachmentAdapter'
|
||||
import { createScratchlistAttachmentAdapter } from '@/lib/scratchlistAttachmentAdapter'
|
||||
@@ -468,6 +468,27 @@ function SessionChatInner(props: SessionChatProps) {
|
||||
const { haptic } = usePlatform()
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const [historyActionPending, setHistoryActionPending] = useState(false)
|
||||
|
||||
const onForkConversation = useCallback(async (messageLocalId?: string) => {
|
||||
setHistoryActionPending(true)
|
||||
try {
|
||||
const result = await props.api.forkConversation(props.session.id, messageLocalId)
|
||||
await navigate({ to: '/sessions/$sessionId', params: { sessionId: result.sessionId } })
|
||||
} finally {
|
||||
setHistoryActionPending(false)
|
||||
}
|
||||
}, [navigate, props.api, props.session.id])
|
||||
|
||||
const onRewindConversation = useCallback(async (messageLocalId: string) => {
|
||||
setHistoryActionPending(true)
|
||||
try {
|
||||
await props.api.rewindConversation(props.session.id, messageLocalId)
|
||||
props.onRefresh()
|
||||
} finally {
|
||||
setHistoryActionPending(false)
|
||||
}
|
||||
}, [props.api, props.onRefresh, props.session.id])
|
||||
const sessionInactive = !props.session.active
|
||||
const inactiveCanResume = inactiveSessionCanResume(
|
||||
props.session,
|
||||
@@ -1049,6 +1070,30 @@ function SessionChatInner(props: SessionChatProps) {
|
||||
[reconciled.blocks, props.hasMoreMessages]
|
||||
)
|
||||
|
||||
// Fork-current must compare against assistant-ui message ids (`kind:id`),
|
||||
// not raw hub message ids — MessageActions receive the rendered card id,
|
||||
// and adjacent assistant blocks join under the first block's id.
|
||||
const latestCompletedBoundaryId = useMemo(() => {
|
||||
if (props.viewMode !== 'tail') return null
|
||||
let candidate: string | null = null
|
||||
let previousRole: ReturnType<typeof visibleBlockRole> | null = null
|
||||
for (const { block, threadMessageId } of assignThreadMessageIds(visibleBlocks)) {
|
||||
const role = visibleBlockRole(block)
|
||||
if (
|
||||
(role === 'user' && block.invokedAt != null)
|
||||
|| (role === 'assistant' && previousRole !== 'assistant')
|
||||
) {
|
||||
candidate = threadMessageId
|
||||
}
|
||||
previousRole = role
|
||||
}
|
||||
return candidate
|
||||
}, [props.viewMode, visibleBlocks])
|
||||
|
||||
const isLatestCompletedBoundary = useCallback((messageId: string) => {
|
||||
return latestCompletedBoundaryId === messageId
|
||||
}, [latestCompletedBoundaryId])
|
||||
|
||||
useEffect(() => {
|
||||
visibleGroupsRef.current = visibleBlocks.filter(isToolGroupBlock)
|
||||
}, [visibleBlocks])
|
||||
@@ -1366,6 +1411,10 @@ function SessionChatInner(props: SessionChatProps) {
|
||||
disabled={sessionInactive}
|
||||
onRefresh={props.onRefresh}
|
||||
onRetryMessage={props.onRetryMessage}
|
||||
historyActionPending={historyActionPending}
|
||||
onForkConversation={controlledByUser ? undefined : onForkConversation}
|
||||
onRewindConversation={controlledByUser ? undefined : onRewindConversation}
|
||||
isLatestCompletedBoundary={isLatestCompletedBoundary}
|
||||
onViewModeChange={props.onViewModeChange}
|
||||
isSyncingTail={props.isSyncingTail}
|
||||
messagesWarning={props.messagesWarning}
|
||||
|
||||
@@ -11,6 +11,14 @@ export default {
|
||||
'message.copy': 'Copy',
|
||||
'message.copied': 'Copied',
|
||||
'message.info': 'Message details',
|
||||
'message.fork': 'Fork',
|
||||
'message.rewind': 'Rewind',
|
||||
'message.fork.confirmTitle': 'Fork conversation',
|
||||
'message.fork.confirmDescription': 'Create a new session from this point?\nThe current session will not be changed.',
|
||||
'message.fork.confirming': 'Forking…',
|
||||
'message.rewind.confirmTitle': 'Rewind conversation',
|
||||
'message.rewind.confirmDescription': 'Rewind this session to this point?\nLater conversation history will be permanently removed. Files will not be changed.',
|
||||
'message.rewind.confirming': 'Rewinding…',
|
||||
'message.shareTurn': 'Share turn as image',
|
||||
'shareTurn.title': 'Share turn as image',
|
||||
'shareTurn.badge': 'Shared turn',
|
||||
|
||||
@@ -11,6 +11,14 @@ export default {
|
||||
'message.copy': '复制',
|
||||
'message.copied': '已复制',
|
||||
'message.info': '消息详情',
|
||||
'message.fork': 'Fork',
|
||||
'message.rewind': 'Rewind',
|
||||
'message.fork.confirmTitle': '分叉对话',
|
||||
'message.fork.confirmDescription': '从此处创建新会话?\n当前会话不会被修改。',
|
||||
'message.fork.confirming': '分叉中…',
|
||||
'message.rewind.confirmTitle': '回退对话',
|
||||
'message.rewind.confirmDescription': '将此会话回退到此处?\n之后的对话历史将永久移除。文件不会被修改。',
|
||||
'message.rewind.confirming': '回退中…',
|
||||
'message.shareTurn': '将本轮对话分享为图片',
|
||||
'shareTurn.title': '将本轮对话分享为图片',
|
||||
'shareTurn.badge': '分享会话',
|
||||
|
||||
@@ -84,7 +84,16 @@ export type SessionMetadataSummary = {
|
||||
flavor?: string | null
|
||||
capabilities?: {
|
||||
terminal?: boolean
|
||||
conversationHistory?: {
|
||||
forkCurrent?: boolean
|
||||
forkAtMessage?: boolean
|
||||
rewindToMessage?: boolean
|
||||
}
|
||||
}
|
||||
conversationHistoryPoints?: Record<string, true>
|
||||
conversationHistoryIndexes?: Record<string, number>
|
||||
conversationHistoryTurns?: Record<string, string>
|
||||
conversationHistoryDiverged?: boolean
|
||||
worktree?: WorktreeMetadata
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user