Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(group): full context per speaker, regenerate one speaker, speaking order (#201 #199 #200)

purple88662fb49f69
diff --git a/src/api/providers/__tests__/context-probe-parsers.test.ts b/src/api/providers/__tests__/context-probe-parsers.test.ts
index 5351fccb..f463304c 100644
--- a/src/api/providers/__tests__/context-probe-parsers.test.ts
+++ b/src/api/providers/__tests__/context-probe-parsers.test.ts
@@ -15,7 +15,7 @@
import { describe, it, expect } from 'vitest'
import {
serverRoot, v1Root, parseLlamaCppProps, parseModelsListContext,
- parseKoboldMaxContext, parseLmStudioModel, parseModelRowContext,
+ parseKoboldMaxContext, parseLmStudioModel, parseModelRowContext, parseOllamaShowContext,
} from '../context-probe'
describe('serverRoot: eine Basis-URL mit und ohne /v1 meint denselben Server', () => {
@@ -179,3 +179,21 @@ describe('LM Studio und die allgemeinen Schluessel', () => {
expect(parseModelRowContext({ id: 'x' })).toEqual({ window: null, trained: null })
})
})
+
+describe('GH #201: an Ollama emulation that names the length outside model_info', () => {
+ it('reads a plain context_length at the top', () => {
+ expect(parseOllamaShowContext({ model_info: {}, context_length: 262144 })).toBe(262144)
+ })
+ it('reads <arch>.context_length at the top, as a pass-through proxy added it', () => {
+ expect(parseOllamaShowContext({ model_info: {}, 'gemma4.context_length': 262144 })).toBe(262144)
+ })
+ it('reads it from details', () => {
+ expect(parseOllamaShowContext({ details: { context_length: '131072' } })).toBe(131072)
+ })
+ it('model_info still wins, as Ollama fills it', () => {
+ expect(parseOllamaShowContext({ model_info: { 'llama.context_length': 8192 }, context_length: 4096 })).toBe(8192)
+ })
+ it('nothing named stays null', () => {
+ expect(parseOllamaShowContext({ model_info: {}, details: { family: 'gemma4' } })).toBeNull()
+ })
+})
diff --git a/src/api/providers/context-probe.ts b/src/api/providers/context-probe.ts
index 12222dc3..cffeff1d 100644
--- a/src/api/providers/context-probe.ts
+++ b/src/api/providers/context-probe.ts
@@ -195,6 +195,21 @@ export function parseOllamaShowContext(info: unknown): number | null {
}
}
}
+ // GH #201: a server that emulates Ollama (KoboldCpp, or a proxy in front
+ // of it) can name the length outside `model_info`: as a plain
+ // `context_length`, as `<arch>.context_length` beside it, or in `details`.
+ // Ollama itself never does, so for Ollama nothing changes.
+ for (const where of [info, prop(info, 'details')]) {
+ if (!isRecord(where)) continue
+ const plain = positiveCount(where.context_length)
+ if (plain) return plain
+ for (const [k, v] of Object.entries(where)) {
+ if (k.endsWith('.context_length')) {
+ const n = positiveCount(v)
+ if (n) return n
+ }
+ }
+ }
const params = prop(info, 'parameters')
if (isRecord(params)) {
const n = positiveCount(params.num_ctx)
diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsx
index 49eecf4c..31d36d0d 100644
--- a/src/components/chat/ChatView.tsx
+++ b/src/components/chat/ChatView.tsx
@@ -32,6 +32,7 @@ import { GoalBar } from './GoalBar'
import { PlanBar } from './PlanBar'
import { LoopBar } from './LoopBar'
import { GroupCostHint } from './GroupCostHint'
+import { GroupRoundBar } from './GroupRoundBar'
import { MemoryDebugToggle } from './MemoryDebugPanel'
import { TokenCounter } from './TokenCounter'
import { ContextDropdown } from './ContextDropdown'
@@ -65,7 +66,7 @@ interface Landing {
}
export function ChatView() {
- const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()
+ const { sendMessage, stopGeneration, isGenerating, isLoadingModel, regenerateMessage, regenerateSpeaker, editAndResend, pendingApproval, approveToolCall, rejectToolCall } = useChat()
// A message from the paired phone in a shared chat goes through this very
// send path (lib/remote-chats-bridge, lib/remote-chat-senders).
useEffect(() => registerChatSender('chat', {
@@ -482,6 +483,7 @@ export function ChatView() {
isThisChatGenerating={activeGenerating}
isLoadingModel={isLoadingModel}
onRegenerate={regenerateMessage}
+ onRegenerateSpeaker={regenerateSpeaker}
onEdit={editAndResend}
pendingApprovalId={pendingApproval?.id ?? null}
onApprove={approveToolCall}
@@ -657,6 +659,9 @@ export function ChatView() {
Flash-Modell, verschiebt also nichts, wenn es fehlt. */}
<FlashChatNotice />
<AgentWorkspaceBadge />
+ {/* GH #200: who answers the next round, and Skip /
+ Stop while one runs. Null outside a group chat. */}
+ <GroupRoundBar onStop={stopGeneration} />
{/* Spacer */}
<div className="flex-1" />
diff --git a/src/components/chat/GroupRoundBar.tsx b/src/components/chat/GroupRoundBar.tsx
new file mode 100644
index 00000000..9e4182a8
--- /dev/null
+++ b/src/components/chat/GroupRoundBar.tsx
@@ -0,0 +1,111 @@
+// The group round, as controls in the session strip (3.0.9, GH #200).
+//
+// Before a round: the speaking order, one chip per member ("1 Walt",
+// "2 Baron"). A click sets a member to sit out the NEXT round only; the
+// round that starts takes the pick away. While a round runs: who speaks,
+// "Skip speaker" (end this turn, go on with the next) and "Stop round".
+//
+// Controls, not sentences: nothing here is a notice to read, so the rule
+// that keeps notices away from the prompt box is not touched.
+import { useMemo } from 'react'
+import { Users, SkipForward, Square } from 'lucide-react'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useGroupRoundStore, skipGroupSpeaker } from '../../stores/groupRoundStore'
+import { availableGroupMembers, groupSpeakers, isGroupChat } from '../../lib/group-chat'
+import { displayModelName } from '../../api/providers'
+
+/** The name a member goes by in this chat: its persona, else its model. */
+export function memberLabel(model: string, speakers: Record<string, { name: string; personaId?: string }>): string {
+ const s = speakers[model]
+ return s?.personaId ? s.name : displayModelName(model)
+}
+
+export function GroupRoundBar({ onStop }: { onStop: () => void }) {
+ const convId = useChatStore((s) => s.activeConversationId)
+ // Three fields, not the conversation: the conversation object changes on
+ // every streaming frame, these only when the group does.
+ const groupModels = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId)?.groupModels)
+ const groupPersonas = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId)?.groupPersonas)
+ const sitOutPick = useChatStore((s) => s.conversations.find((c) => c.id === s.activeConversationId)?.groupSitOut)
+ const setGroupSitOut = useChatStore((s) => s.setGroupSitOut)
+ const models = useModelStore((s) => s.models)
+ const inventoryLoaded = useModelStore((s) => s.inventoryLoaded)
+ const personas = useSettingsStore((s) => s.personas)
+ const live = useGroupRoundStore((s) => (convId ? s.live[convId] : undefined))
+ const table = useMemo(
+ () => availableGroupMembers(groupModels ?? [], models, inventoryLoaded),
+ [groupModels, models, inventoryLoaded],
+ )
+ const speakers = useMemo(() => groupSpeakers(table, groupPersonas, personas), [table, groupPersonas, personas])
+
+ if (!convId || !isGroupChat(groupModels)) return null
+
+ if (live) {
+ return (
+ <div data-testid="group-round-bar" data-state="running" className="flex items-center gap-1 min-w-0 t-micro text-gray-500">
+ <Users size={10} className="shrink-0 text-purple-400" />
+ <span className="truncate" data-testid="group-round-speaker">
+ {memberLabel(live.speaker, speakers)} <span className="lu-hud-num">{live.index + 1}/{live.total}</span>
+ </span>
+ <button
+ onClick={() => skipGroupSpeaker(convId)}
+ disabled={live.index + 1 >= live.total}
+ data-testid="group-skip-speaker"
+ title={live.index + 1 >= live.total ? 'This is the last speaker of the round' : 'Stop this speaker and go on with the next one'}
+ className="shrink-0 flex items-center gap-0.5 px-1.5 py-0.5 rounded border border-gray-200 dark:border-white/[0.08] hover:border-gray-400 dark:hover:border-white/20 hover:text-gray-700 dark:hover:text-gray-200 disabled:opacity-40 disabled:pointer-events-none transition-colors"
+ >
+ <SkipForward size={9} /> Skip speaker
+ </button>
+ <button
+ onClick={onStop}
+ data-testid="group-stop-round"
+ title="Stop the whole round"
+ className="shrink-0 flex items-center gap-0.5 px-1.5 py-0.5 rounded border border-gray-200 dark:border-white/[0.08] hover:border-red-400/60 hover:text-red-500 transition-colors"
+ >
+ <Square size={8} /> Stop round
+ </button>
+ </div>
+ )
+ }
+
+ const sitOut = sitOutPick ?? []
+ const answering = table.filter((m) => !sitOut.includes(m))
+ return (
+ <div data-testid="group-round-bar" data-state="idle" className="flex items-center gap-1 min-w-0 t-micro text-gray-500">
+ <Users size={10} className="shrink-0 text-purple-400" />
+ <span className="shrink-0">Next round:</span>
+ <div className="flex items-center gap-0.5 min-w-0 overflow-x-auto scrollbar-thin">
+ {table.map((model, i) => {
+ const out = sitOut.includes(model)
+ // The last one answering cannot sit out too: a round needs a speaker.
+ const lastOne = !out && answering.length <= 1
+ return (
+ <button
+ key={model}
+ data-testid="group-next-speaker"
+ data-model={model}
+ aria-pressed={!out}
+ disabled={lastOne}
+ onClick={() => setGroupSitOut(convId, out ? sitOut.filter((m) => m !== model) : [...sitOut, model])}
+ title={out
+ ? `${memberLabel(model, speakers)} sits out the next round. Click to let it answer.`
+ : lastOne
+ ? 'At least one member answers'
+ : `Click to let ${memberLabel(model, speakers)} sit out the next round only`}
+ className={`shrink-0 flex items-center gap-1 px-1.5 py-0.5 rounded border transition-colors ${
+ out
+ ? 'border-dashed border-gray-300 dark:border-white/10 text-gray-400 line-through'
+ : 'border-purple-400/40 text-purple-600 dark:text-purple-300 hover:border-purple-400'
+ } disabled:cursor-default`}
+ >
+ <span className="lu-hud-num">{i + 1}</span>
+ <span className="truncate max-w-[9rem]">{memberLabel(model, speakers)}</span>
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 06512ec7..9b324e5e 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -2,7 +2,7 @@ import { ChatAttachment } from './ChatAttachment'
import { ChatFileChip } from './ChatFileChip'
import { FILE_ONLY_TEXT } from '../../lib/chat-files'
import { motion } from 'framer-motion'
-import { User, Copy, Check, Pencil, RefreshCw, Wrench, Trash2, Scissors, Unlink, Film, Music, GitBranch } from 'lucide-react'
+import { User, Copy, Check, Pencil, RefreshCw, Wrench, Trash2, Scissors, Unlink, Film, Music, GitBranch, ListRestart } from 'lucide-react'
import { useState, useRef, useEffect, useMemo, memo } from 'react'
import { MarkdownRenderer } from './MarkdownRenderer'
import { closeOpenMarkdown } from '../../lib/streaming-markdown'
@@ -46,6 +46,9 @@ interface Props {
* ONE stable function to every bubble — a per-message closure would be a new
* prop on every render and defeat the memo() below. */
onRegenerate?: (messageId: string) => void
+ /** GH #199: a group speaker's answer also offers the whole round again,
+ * as an action of its own beside Regenerate. */
+ onRegenerateRound?: (messageId: string) => void
/** "Save & resend" of an edited user message. False when nothing could be
* sent; the edit is then saved instead of lost. */
onEdit?: (messageId: string, newContent: string) => boolean
@@ -77,7 +80,7 @@ interface Props {
declined?: boolean
}
-function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming, speakerName, declined, forkKey, forkIndex, forkTotal, onSwitchFork, onBranch }: Props) {
+function MessageBubbleImpl({ message, onRegenerate, onRegenerateRound, onEdit, pendingApprovalId, onApprove, onReject, isLast, isStreaming, speakerName, declined, forkKey, forkIndex, forkTotal, onSwitchFork, onBranch }: Props) {
const [copied, setCopied] = useState(false)
const [isEditing, setIsEditing] = useState(false)
const [editContent, setEditContent] = useState('')
@@ -688,7 +691,10 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
<button onClick={actions.edit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit response" title="Edit"><Pencil size={12} /></button>
)}
{actions.regenerate && (
- <button onClick={actions.regenerate} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title="Regenerate"><RefreshCw size={12} /></button>
+ <button onClick={actions.regenerate} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title={onRegenerateRound ? 'Regenerate this answer' : 'Regenerate'}><RefreshCw size={12} /></button>
+ )}
+ {!isUser && onRegenerateRound && (
+ <button onClick={() => onRegenerateRound(message.id)} data-testid="regenerate-round" className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate whole round" title="Regenerate whole round: every speaker answers this message again"><ListRestart size={12} /></button>
)}
<button onClick={actions.copy} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Copy message" title={copied ? 'Copied' : 'Copy'}>
{copied ? <Check size={12} className="text-green-500" /> : <Copy size={12} />}
diff --git a/src/components/chat/MessageList.tsx b/src/components/chat/MessageList.tsx
index 407d996f..a9ceb21c 100644
--- a/src/components/chat/MessageList.tsx
+++ b/src/components/chat/MessageList.tsx
@@ -16,6 +16,11 @@ import { useAgentModeStore } from '../../stores/agentModeStore'
import { latestRefusalId, refusalNoticeApplies } from '../../lib/refusal-detect'
import { GreetingSwitcher } from './GreetingSwitcher'
import { forkMarks } from '../../lib/chat-forks'
+import { hasLaterRounds, isSpeakerTurn, laterAnswersInRound } from '../../lib/group-rounds'
+import { historyTrimNote } from '../../lib/history-trim-note'
+import { displayModelName } from '../../api/providers'
+import { Modal } from '../ui/Modal'
+import { ModalActions, ModalButton } from '../ui/ModalActions'
/**
* Above this many visible messages the transcript stops paying full layout +
@@ -65,6 +70,9 @@ interface Props {
isThisChatGenerating?: boolean
isLoadingModel?: boolean
onRegenerate?: (conversationId: string, assistantMessageId: string) => void
+ /** GH #199: one speaker of a group round answers again ('only'), or it and
+ * every later speaker of the round ('from-here'). */
+ onRegenerateSpeaker?: (conversationId: string, assistantMessageId: string, mode: 'only' | 'from-here') => Promise<boolean>
/** Save & resend. False when nothing could be sent. */
onEdit?: (conversationId: string, messageId: string, newContent: string) => boolean | void
/** Tool-call id awaiting user approval — when set, the matching tool
@@ -74,7 +82,7 @@ interface Props {
onReject?: () => void
}
-export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel, onRegenerate, onEdit, pendingApprovalId, onApprove, onReject }: Props) {
+export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel, onRegenerate, onRegenerateSpeaker, onEdit, pendingApprovalId, onApprove, onReject }: Props) {
const showTyping = isThisChatGenerating ?? isGenerating
// The question of the first use of computer control is open in this conversation.
const chatAsked = useComputerStore((s) => !!s.chatAsk && !s.chatAsk.voice && (s.chatAsk.conversationId === null || s.chatAsk.conversationId === useChatStore.getState().activeConversationId))
@@ -127,14 +135,39 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
// (React 19 `refs`). Both readers below are user-event handlers, which never
// run before the effects of the render they belong to, so they still only
// ever see the current conversation and callbacks.
- const bind = useRef({ conversation, onRegenerate, onEdit })
- useEffect(() => { bind.current = { conversation, onRegenerate, onEdit } })
+ const bind = useRef({ conversation, onRegenerate, onRegenerateSpeaker, onEdit })
+ useEffect(() => { bind.current = { conversation, onRegenerate, onRegenerateSpeaker, onEdit } })
+
+ // GH #199: in a group, Regenerate on a speaker asks that speaker again. With
+ // later speakers already answered, the person picks first; the question
+ // stays open here until they do.
+ const [askRegen, setAskRegen] = useState<{ convId: string; messageId: string; later: number; laterRounds: boolean } | null>(null)
const handleRegenerate = useCallback((messageId: string) => {
+ const { conversation: c, onRegenerate: cb, onRegenerateSpeaker: one } = bind.current
+ if (!c) return
+ if (one && (c.groupModels?.length ?? 0) >= 2 && isSpeakerTurn(c.messages, messageId)) {
+ const later = laterAnswersInRound(c.messages, messageId).length
+ if (later === 0) void one(c.id, messageId, 'only')
+ else setAskRegen({ convId: c.id, messageId, later, laterRounds: hasLaterRounds(c.messages, messageId) })
+ return
+ }
+ if (cb) cb(c.id, messageId)
+ }, [])
+
+ // "Regenerate whole round": the round's question again, every speaker.
+ const handleRegenerateRound = useCallback((messageId: string) => {
const { conversation: c, onRegenerate: cb } = bind.current
if (c && cb) cb(c.id, messageId)
}, [])
+ const answerRegen = (mode: 'only' | 'from-here') => {
+ const ask = askRegen
+ setAskRegen(null)
+ const one = bind.current.onRegenerateSpeaker
+ if (ask && one) void one(ask.convId, ask.messageId, mode)
+ }
+
const handleEdit = useCallback((messageId: string, content: string): boolean => {
const { conversation: c, onEdit: cb } = bind.current
return !!c && !!cb && cb(c.id, messageId, content) !== false
@@ -195,6 +228,8 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
// Die Verdichtungslinien. Berechnet aus der VOLLEN Nachrichtenliste, weil
// der Schnittpunkt auf eine gefilterte Nachricht zeigen kann, aber
// angezeigt an sichtbaren Zeilen — siehe compactionAnchors.
+ const groupOn = (groupModels?.length ?? 0) >= 2
+
const compactAt = compactionAnchors(
conversation.messages,
visibleMessages.map((m) => m.id),
@@ -202,6 +237,7 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
)
return (
+ <>
<div
ref={scrollRef}
className="flex-1 overflow-y-auto scrollbar-thin py-4"
@@ -233,6 +269,18 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
key={message.id}
style={skipOffscreen && index < tailStart ? SKIPPABLE : undefined}
>
+ {message.role === 'assistant' && message.historyTrim && (
+ <div className="px-3 pt-1" data-testid="history-trim-note">
+ <Hinweis>
+ <span className="break-words">
+ {historyTrimNote(
+ message.historyTrim,
+ groupOn && message.modelId ? (speakerNameOf(message, speakers, authors) ?? displayModelName(message.modelId)) : undefined,
+ )}
+ </span>
+ </Hinweis>
+ </div>
+ )}
{message.role === 'system' && message.notice ? (
// Schlichte Zeile, keine Blase: eine Blase wuerde behaupten,
// das Modell habe es gesagt. Und kein Kasten mehr darum: der
@@ -256,6 +304,9 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
onRegenerate={message.role === 'assistant' && onRegenerate && !isGenerating && !message.greetings
? handleRegenerate
: undefined}
+ onRegenerateRound={groupOn && message.role === 'assistant' && onRegenerate && !isGenerating && message.modelId
+ ? handleRegenerateRound
+ : undefined}
onEdit={message.role === 'user' && onEdit && !isGenerating
? handleEdit
: undefined}
@@ -299,6 +350,21 @@ export function MessageList({ isGenerating, isThisChatGenerating, isLoadingModel
)}
</div>
</div>
+ {/* GH #199: later speakers of this round already answered. Ask before
+ anything moves. Outside the scrolling list, whose mask would clip it. */}
+ <Modal open={!!askRegen} onClose={() => setAskRegen(null)} title="Regenerate this answer" maxWidth="max-w-md">
+ <p className="t-small text-gray-600 dark:text-gray-300" data-testid="regen-speaker-question">
+ {askRegen?.later === 1 ? 'One later speaker' : `${askRegen?.later ?? 0} later speakers`} of this round already answered.
+ Keep {askRegen?.later === 1 ? 'that answer' : 'their answers'}, or let {askRegen?.later === 1 ? 'it' : 'them'} answer again after the new one?
+ {askRegen?.laterRounds ? ' Later rounds move into the earlier version either way; the arrows bring them back.' : ''}
+ </p>
+ <ModalActions>
+ <ModalButton variant="quiet" onClick={() => setAskRegen(null)}>Cancel</ModalButton>
+ <ModalButton data-testid="regen-from-here" onClick={() => answerRegen('from-here')}>Regenerate from here</ModalButton>
+ <ModalButton data-testid="regen-keep-later" variant="primary" onClick={() => answerRegen('only')}>Keep later answers</ModalButton>
+ </ModalActions>
+ </Modal>
+ </>
)
}
diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsx
index 00fa9aff..dd90e590 100644
--- a/src/components/chat/PluginsDropdown.tsx
+++ b/src/components/chat/PluginsDropdown.tsx
@@ -1,11 +1,12 @@
import { lazy, Suspense, useRef, useState } from 'react'
import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'
import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'
-import { Plug, ChevronDown, Bone, User, Users, Sparkles, X } from 'lucide-react'
+import { Plug, ChevronDown, ChevronUp, Bone, User, Users, Sparkles, X, GripVertical } from 'lucide-react'
import { useSettingsStore } from '../../stores/settingsStore'
import { useChatStore } from '../../stores/chatStore'
import { useModelStore } from '../../stores/modelStore'
import { GROUP_CHAT_MAX, isGroupChat, groupChatRows } from '../../lib/group-chat'
+import { moveMember } from '../../lib/group-rounds'
import { resolveChatPersona } from '../../lib/chat-persona'
import type { CavemanMode } from '../../types/settings'
import { displayModelName } from '../../api/providers/registry'
@@ -61,6 +62,8 @@ export function PluginsDropdown({
const [groupOpen, setGroupOpen] = useState(false)
// Which participant's persona list is open, by model name.
const [personaFor, setPersonaFor] = useState<string | null>(null)
+ // GH #200: the member being dragged in the speaking order, by index.
+ const [dragFrom, setDragFrom] = useState<number | null>(null)
const setActivePersona = useSettingsStore((s) => s.setActivePersona)
const activePersonaId = useSettingsStore((s) => s.activePersonaId)
const allPersonas = useSettingsStore((s) => s.personas)
@@ -379,6 +382,59 @@ export function PluginsDropdown({
<p className="px-2 pb-0.5 text-[0.5rem] leading-snug text-gray-400">
Pick 2 to {GROUP_CHAT_MAX} models. They answer in turn on every message, and each sees what the others said. Each one can speak as its own persona.
</p>
+ {/* GH #200: the order is the order of the round. Shown, and
+ changed by dragging a row or with its arrows; before,
+ it was the order of ticking and nowhere to be seen. */}
+ {groupModels.length >= 2 && (
+ <div data-testid="group-order" className="mb-1 pb-1 border-b border-gray-200/60 dark:border-white/[0.04]">
+ <p className="px-2 pb-0.5 t-micro leading-snug text-gray-400">Speaking order. Drag a row or use the arrows.</p>
+ {groupModels.map((name, i) => {
+ const persona = allPersonas.find((p) => p.id === groupPersonas?.[name])
+ const label = persona?.name ?? displayModelName(name)
+ return (
+ <div
+ key={name}
+ data-testid="group-order-row"
+ data-model={name}
+ draggable
+ onDragStart={(e) => { setDragFrom(i); e.dataTransfer.effectAllowed = 'move' }}
+ onDragOver={(e) => { if (dragFrom !== null) e.preventDefault() }}
+ onDrop={(e) => {
+ e.preventDefault()
+ if (dragFrom !== null) setGroupModels(activeConvId, moveMember(groupModels, dragFrom, i))
+ setDragFrom(null)
+ }}
+ onDragEnd={() => setDragFrom(null)}
+ className={`flex items-center gap-1 px-1.5 py-0.5 rounded cursor-grab active:cursor-grabbing transition-colors ${dragFrom === i ? 'opacity-50' : 'hover:bg-purple-500/5'}`}
+ >
+ <GripVertical size={9} className="shrink-0 text-gray-400" />
+ <span className="lu-hud-num w-3 shrink-0 t-micro text-purple-500 dark:text-purple-400">{i + 1}</span>
+ <span className="flex-1 min-w-0 truncate t-micro text-gray-600 dark:text-gray-300" title={displayModelName(name)}>{label}</span>
+ <button
+ disabled={i === 0}
+ onClick={() => setGroupModels(activeConvId, moveMember(groupModels, i, i - 1))}
+ aria-label={`Move ${label} up`}
+ title="Speak earlier"
+ data-testid="group-order-up"
+ className="shrink-0 p-0.5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-500/10 disabled:opacity-30 disabled:pointer-events-none"
+ >
+ <ChevronUp size={9} />
+ </button>
+ <button
+ disabled={i === groupModels.length - 1}
+ onClick={() => setGroupModels(activeConvId, moveMember(groupModels, i, i + 1))}
+ aria-label={`Move ${label} down`}
+ title="Speak later"
+ data-testid="group-order-down"
+ className="shrink-0 p-0.5 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-500/10 disabled:opacity-30 disabled:pointer-events-none"
+ >
+ <ChevronDown size={9} />
+ </button>
+ </div>
+ )
+ })}
+ </div>
+ )}
{groupRows.map((m) => {
const on = groupModels.includes(m.name)
const full = !on && groupModels.length >= GROUP_CHAT_MAX
@@ -413,7 +469,12 @@ export function PluginsDropdown({
: 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'
}`}
>
- {on && <div className={`w-1 h-1 rounded-full shrink-0 ${m.unavailable ? 'bg-gray-400' : 'bg-purple-400'}`} />}
+ {/* GH #200: the place in the round, where the dot was. */}
+ {on && (
+ <span data-testid="group-participant-place" aria-hidden="true" className={`lu-hud-num w-3 shrink-0 t-micro ${m.unavailable ? 'text-gray-400' : 'text-purple-500 dark:text-purple-400'}`}>
+ {groupModels.indexOf(m.name) + 1}
+ </span>
+ )}
<span
className={`text-[0.55rem] font-medium truncate ${m.unavailable ? 'line-through' : ''}`}
title={m.unavailable
diff --git a/src/components/chat/__tests__/group-order-and-round-controls.test.tsx b/src/components/chat/__tests__/group-order-and-round-controls.test.tsx
new file mode 100644
index 00000000..fa8e14ee
--- /dev/null
+++ b/src/components/chat/__tests__/group-order-and-round-controls.test.tsx
@@ -0,0 +1,199 @@
+// @vitest-environment jsdom
+/**
+ * 3.0.9, GH #199, #200, #201: what a person sees and clicks in a group chat.
+ *
+ * - #200: the group menu shows the speaking order (1, 2, 3) and changes it
+ * with arrows or by dragging; the session strip names who answers the next
+ * round, lets a member sit it out, and offers Skip speaker and Stop round
+ * while a round runs.
+ * - #199: Regenerate on a speaker with later answers asks first; "Regenerate
+ * whole round" is an action of its own.
+ * - #201: an answer whose request left older turns out says so.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/group-order-and-round-controls.test.tsx
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { PluginsDropdown } from '../PluginsDropdown'
+import { MessageList } from '../MessageList'
+import { GroupRoundBar } from '../GroupRoundBar'
+import { useChatStore } from '../../../stores/chatStore'
+import { useModelStore } from '../../../stores/modelStore'
+import { useSettingsStore } from '../../../stores/settingsStore'
+import { useGroupRoundStore, groupTurnStarted, groupRoundEnded } from '../../../stores/groupRoundStore'
+import { BUILT_IN_PERSONAS, DEFAULT_SETTINGS } from '../../../lib/constants'
+import type { AIModel } from '../../../types/models'
+import type { Message } from '../../../types/chat'
+
+const A = 'openai::walt'
+const B = 'openai::baron'
+const C = 'openai::clara'
+const textModel = (name: string): AIModel => ({ name, type: 'text' } as AIModel)
+
+let convId = ''
+beforeEach(() => {
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGroupRoundStore.setState({ live: {} })
+ useModelStore.setState({ models: [textModel(A), textModel(B), textModel(C)], activeModel: A, inventoryLoaded: true })
+ useSettingsStore.setState({ settings: { ...DEFAULT_SETTINGS }, personas: [...BUILT_IN_PERSONAS] })
+ convId = useChatStore.getState().createConversation(A, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useChatStore.getState().setGroupModels(convId, [A, B, C])
+})
+afterEach(cleanup)
+
+const conversation = () => useChatStore.getState().conversations.find((c) => c.id === convId)!
+const orderShown = () => screen.getAllByTestId('group-order-row').map((r) => r.getAttribute('data-model'))
+
+function openGroupMenu() {
+ render(<PluginsDropdown openUpward />)
+ fireEvent.click(screen.getByRole('button', { name: /Plugins/ }))
+ fireEvent.click(screen.getByRole('button', { name: /Group chat/ }))
+}
+
+describe('GH #200: the speaking order in the group menu', () => {
+ it('is shown, numbered, in the order of the round', () => {
+ openGroupMenu()
+ expect(orderShown()).toEqual([A, B, C])
+ expect(screen.getAllByTestId('group-order-row').map((r) => r.textContent)).toEqual(['1walt', '2baron', '3clara'])
+ // The place also stands at each ticked model in the list.
+ expect(screen.getAllByTestId('group-participant-place').map((p) => p.textContent)).toEqual(['1', '2', '3'])
+ })
+
+ it('the arrows move a member one place', () => {
+ openGroupMenu()
+ fireEvent.click(screen.getByRole('button', { name: 'Move clara up' }))
+ expect(conversation().groupModels).toEqual([A, C, B])
+ fireEvent.click(screen.getByRole('button', { name: 'Move walt down' }))
+ expect(conversation().groupModels).toEqual([C, A, B])
+ expect(orderShown()).toEqual([C, A, B])
+ // The ends cannot move further.
+ expect((screen.getByRole('button', { name: 'Move clara up' }) as HTMLButtonElement).disabled).toBe(true)
+ expect((screen.getByRole('button', { name: 'Move baron down' }) as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('dragging a row drops it at the place of the row it lands on', () => {
+ openGroupMenu()
+ const rows = screen.getAllByTestId('group-order-row')
+ const data = { effectAllowed: '', setData: () => {}, getData: () => '' }
+ fireEvent.dragStart(rows[2], { dataTransfer: data })
+ fireEvent.dragOver(rows[0], { dataTransfer: data })
+ fireEvent.drop(rows[0], { dataTransfer: data })
+ expect(conversation().groupModels).toEqual([C, A, B])
+ })
+})
+
+describe('GH #200: the round bar', () => {
+ it('names the next round in order, and a click lets a member sit it out', () => {
+ render(<GroupRoundBar onStop={() => {}} />)
+ const chips = () => screen.getAllByTestId('group-next-speaker')
+ expect(chips().map((c) => c.textContent)).toEqual(['1walt', '2baron', '3clara'])
+ fireEvent.click(chips()[0])
+ expect(conversation().groupSitOut).toEqual([A])
+ expect(chips()[0].getAttribute('aria-pressed')).toBe('false')
+ fireEvent.click(chips()[0])
+ expect(conversation().groupSitOut).toBeUndefined()
+ })
+
+ it('the last one answering cannot sit out too', () => {
+ useChatStore.getState().setGroupSitOut(convId, [A, B])
+ render(<GroupRoundBar onStop={() => {}} />)
+ expect((screen.getAllByTestId('group-next-speaker')[2] as HTMLButtonElement).disabled).toBe(true)
+ })
+
+ it('while a round runs: who speaks, Skip speaker and Stop round', () => {
+ const skip = vi.fn()
+ const stop = vi.fn()
+ groupTurnStarted(convId, { speaker: B, index: 1, total: 3 }, skip)
+ render(<GroupRoundBar onStop={stop} />)
+ expect(screen.getByTestId('group-round-speaker').textContent).toBe('baron 2/3')
+ fireEvent.click(screen.getByTestId('group-skip-speaker'))
+ expect(skip).toHaveBeenCalledTimes(1)
+ fireEvent.click(screen.getByTestId('group-stop-round'))
+ expect(stop).toHaveBeenCalledTimes(1)
+ groupRoundEnded(convId)
+ })
+
+ it('the last speaker has nobody to skip to', () => {
+ groupTurnStarted(convId, { speaker: C, index: 2, total: 3 }, () => {})
+ render(<GroupRoundBar onStop={() => {}} />)
+ expect((screen.getByTestId('group-skip-speaker') as HTMLButtonElement).disabled).toBe(true)
+ groupRoundEnded(convId)
+ })
+
+ it('negative control: nothing in a chat that is not a group', () => {
+ useChatStore.getState().setGroupModels(convId, [])
+ const { container } = render(<GroupRoundBar onStop={() => {}} />)
+ expect(container.innerHTML).toBe('')
+ })
+})
+
+function seedRound(extra: Partial<Message>[] = []) {
+ const messages: Message[] = [
+ { id: 'u1', role: 'user', content: 'go', timestamp: 1 },
+ { id: 'a1', role: 'assistant', content: 'walt says', modelId: A, timestamp: 2 },
+ { id: 'b1', role: 'assistant', content: 'baron says', modelId: B, timestamp: 3 },
+ { id: 'c1', role: 'assistant', content: 'clara says', modelId: C, timestamp: 4 },
+ ].map((m, i) => ({ ...m, ...(extra[i] ?? {}) })) as Message[]
+ useChatStore.setState((s) => ({
+ conversations: s.conversations.map((c) => (c.id === convId ? { ...c, messages } : c)),
+ }))
+}
+
+/** The Regenerate of the n-th answer (0 walt, 1 baron, 2 clara). */
+const regenerateOn = (n: number) => screen.getAllByRole('button', { name: 'Regenerate response' })[n]
+
+describe('GH #199: regenerate in a group', () => {
+ it('a speaker with later answers asks first: keep them, or from here', () => {
+ seedRound()
+ const one = vi.fn(async () => true)
+ const whole = vi.fn()
+ render(<MessageList isGenerating={false} onRegenerate={whole} onRegenerateSpeaker={one} />)
+ fireEvent.click(regenerateOn(1))
+ expect(one).not.toHaveBeenCalled()
+ expect(screen.getByTestId('regen-speaker-question').textContent).toContain('One later speaker of this round already answered.')
+ fireEvent.click(screen.getByTestId('regen-keep-later'))
+ expect(one).toHaveBeenCalledWith(convId, 'b1', 'only')
+
+ fireEvent.click(regenerateOn(0))
+ expect(screen.getByTestId('regen-speaker-question').textContent).toContain('2 later speakers')
+ fireEvent.click(screen.getByTestId('regen-from-here'))
+ expect(one).toHaveBeenLastCalledWith(convId, 'a1', 'from-here')
+ expect(whole).not.toHaveBeenCalled()
+ })
+
+ it('the last speaker regenerates at once, nothing to ask', () => {
+ seedRound()
+ const one = vi.fn(async () => true)
+ render(<MessageList isGenerating={false} onRegenerate={() => {}} onRegenerateSpeaker={one} />)
+ fireEvent.click(regenerateOn(2))
+ expect(screen.queryByTestId('regen-speaker-question')).toBeNull()
+ expect(one).toHaveBeenCalledWith(convId, 'c1', 'only')
+ })
+
+ it('"Regenerate whole round" is its own action', () => {
+ seedRound()
+ const one = vi.fn(async () => true)
+ const whole = vi.fn()
+ render(<MessageList isGenerating={false} onRegenerate={whole} onRegenerateSpeaker={one} />)
+ fireEvent.click(screen.getAllByTestId('regenerate-round')[1])
+ expect(whole).toHaveBeenCalledWith(convId, 'b1')
+ expect(one).not.toHaveBeenCalled()
+ })
+})
+
+describe('GH #201: a trimmed request is said in the chat', () => {
+ it('the answer whose request left turns out carries the line, with its speaker and window', () => {
+ seedRound([{}, {}, { historyTrim: { dropped: 12, window: 262144 } }])
+ render(<MessageList isGenerating={false} />)
+ const notes = screen.getAllByTestId('history-trim-note')
+ expect(notes).toHaveLength(1)
+ expect(notes[0].textContent).toBe('12 earlier messages were not sent to baron: they no longer fit its 256K context. The chat itself keeps them.')
+ })
+
+ it('negative control: no line where the whole chat went out', () => {
+ seedRound()
+ render(<MessageList isGenerating={false} />)
+ expect(screen.queryByTestId('history-trim-note')).toBeNull()
+ })
+})
diff --git a/src/hooks/__tests__/chat-budget-wiring.test.ts b/src/hooks/__tests__/chat-budget-wiring.test.ts
index 2dcb6b5c..90e9cea4 100644
--- a/src/hooks/__tests__/chat-budget-wiring.test.ts
+++ b/src/hooks/__tests__/chat-budget-wiring.test.ts
@@ -61,7 +61,8 @@ describe('a group round is budgeted per model', () => {
describe('compare caps the shared base before the fan-out', () => {
it('takes the tightest budget of the two sides', () => {
expect(compare).toMatch(/sharedChatSendBudget\(/)
- expect(compare).toMatch(/applySendBudget\(chatMessages, budget\)/)
+ // GH #201: with the hysteresis only where a side is paid.
+ expect(compare).toMatch(/applySendBudget\(chatMessages, budget, \{ hysteresis, notice: 'chat' \}\)/)
})
it('streams the budgeted array to BOTH sides, not the raw history', () => {
diff --git a/src/hooks/__tests__/group-chat-sends-the-picked-context.test.ts b/src/hooks/__tests__/group-chat-sends-the-picked-context.test.ts
new file mode 100644
index 00000000..5f4de8f1
--- /dev/null
+++ b/src/hooks/__tests__/group-chat-sends-the-picked-context.test.ts
@@ -0,0 +1,162 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * GH #201: a group chat on two local 256K models ("256K · max" picked for
+ * both) sent only about 128K-131K tokens of a 215K story, round after round,
+ * and the request carried an agent's note ("The original task still stands
+ * ... re-read that specific file"). Plain chat on the same model was not cut.
+ *
+ * The cause was the send budget of a conversation: 0.8 of the window with the
+ * A3 hysteresis on top, so the trim engaged at 0.92 of the window and then
+ * dropped to 0.7 x 0.8 = 0.56 of it. The stored chat is always the full one,
+ * so every later round was over the trigger again and dropped to 0.56 again.
+ *
+ * Driven through the real `useChat().sendMessage`, only the network and the
+ * window lookup replaced: what is asserted is the request each model receives.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: () => 'cloud',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+// Both members run on a server on this machine, as in the report.
+vi.mock('../../lib/lan-openai-slot', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../lib/lan-openai-slot')>()),
+ sendsToALanBackend: () => true,
+}))
+// "256K · max" picked and loaded, as the server reported it.
+vi.mock('../../lib/context-compaction', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../lib/context-compaction')>()),
+ getChatWindowTokens: async () => 262144,
+}))
+
+import { useChat } from '../useChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { __resetRunLanesForTests } from '../../lib/run-lanes'
+import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../../lib/constants'
+import { estimateMessageTokens } from '../../lib/context-compaction'
+import { chatSendBudget } from '../../lib/chat-send-budget'
+import type { Message } from '../../types/chat'
+
+const A = 'openai::walt'
+const B = 'openai::baron'
+
+interface WireMessage { role: string; content: string }
+interface Request { model: string; messages: WireMessage[] }
+let requests: Request[] = []
+
+beforeEach(() => {
+ requests = []
+ __resetRunLanesForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useModelStore.setState({ models: [], activeModel: A })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off' },
+ personas: [...BUILT_IN_PERSONAS],
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },
+ }))
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })
+ const body = JSON.parse(String((init as RequestInit).body)) as Request
+ requests.push(body)
+ return new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: 'つづき。' } }] })}\n\ndata: [DONE]\n\n`, {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+/** A Japanese story of about `tokens` tokens by the app's own estimate, told
+ * by the user and the two members in turn. */
+function story(tokens: number): Message[] {
+ const line = '物語はまだ続いている。'.repeat(180)
+ const out: Message[] = []
+ let i = 0
+ while (estimateMessageTokens(out.map((m) => ({ role: m.role, content: m.content })) as never) < tokens) {
+ const who = i % 3
+ out.push(who === 0
+ ? { id: `m${i}`, role: 'user', content: `第${i}話 ${line}`, timestamp: i }
+ : { id: `m${i}`, role: 'assistant', content: `第${i}話 ${line}`, modelId: who === 1 ? A : B, timestamp: i })
+ i++
+ }
+ return out
+}
+
+function openGroupWith(messages: Message[]): string {
+ const convId = useChatStore.getState().createConversation(A, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useChatStore.getState().setGroupModels(convId, [A, B])
+ useChatStore.setState((s) => ({
+ conversations: s.conversations.map((c) => (c.id === convId ? { ...c, messages } : c)),
+ }))
+ return convId
+}
+
+const wireSize = (r: Request) => estimateMessageTokens(r.messages as never)
+const allText = (r: Request) => r.messages.map((m) => m.content).join('\n')
+const answers = (id: string) =>
+ useChatStore.getState().conversations.find((c) => c.id === id)!.messages.filter((m) => m.role === 'assistant').slice(-2)
+
+async function round(text: string) {
+ const { result } = renderHook(() => useChat())
+ await act(async () => { await result.current.sendMessage(text) })
+}
+
+describe('GH #201: a group member is budgeted by the context picked for it', () => {
+ // The report's 215K tokens by the server's count are about 245K by the
+ // app's estimate, which runs ahead on Japanese: the stored usage of a
+ // request the app estimated at 146.8K said 129.5K. 245K is past the old
+ // trigger (0.92 x 262144 = 241172) and inside the window.
+ it('a 215K story goes out whole to a 256K member, as in plain chat', async () => {
+ const history = story(245_000)
+ const convId = openGroupWith(history)
+ await round('続けて')
+
+ expect(requests.map((r) => r.model)).toEqual(['walt', 'baron'])
+ // Every turn of the story reached the first speaker; before the fix the
+ // request held about 0.56 x 262144 = 146800 estimated tokens.
+ expect(wireSize(requests[0])).toBeGreaterThan(245_000)
+ expect(allText(requests[0])).toContain('第0話')
+ expect(allText(requests[0])).not.toMatch(/trimmed|not included/)
+ expect(answers(convId).every((m) => m.historyTrim === undefined)).toBe(true)
+ })
+
+ it('a story larger than the window is trimmed to the window, not to half of it', async () => {
+ const history = story(300_000)
+ const convId = openGroupWith(history)
+ await round('続けて')
+
+ const budget = chatSendBudget({ providerId: 'openai', modelWindow: 262144, contextDecay: true, localBackend: true })!
+ expect(budget).toBe(262144 - 8192)
+ for (const r of requests) {
+ expect(wireSize(r)).toBeLessThanOrEqual(budget)
+ // Not the old 0.56 of the window: the trim keeps what fits.
+ expect(wireSize(r)).toBeGreaterThan(budget * 0.9)
+ }
+ // The note the model reads is a conversation's, not an agent's.
+ const text = allText(requests[0])
+ expect(text).toMatch(/\[Note: \d+ earlier messages of this conversation are not included here/)
+ expect(text).not.toContain('re-read')
+ expect(text).not.toContain('original task')
+ // And the chat says so next to each answer.
+ const said = answers(convId)
+ expect(said.map((m) => m.historyTrim?.window)).toEqual([262144, 262144])
+ expect(said.every((m) => (m.historyTrim?.dropped ?? 0) > 0)).toBe(true)
+ })
+})
diff --git a/src/hooks/__tests__/group-round-control.test.ts b/src/hooks/__tests__/group-round-control.test.ts
new file mode 100644
index 00000000..2ec9a0b2
--- /dev/null
+++ b/src/hooks/__tests__/group-round-control.test.ts
@@ -0,0 +1,220 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * 3.0.9, GH #199 and GH #200: a person decides more about a group round.
+ *
+ * - #199: "Regenerate" on one speaker's answer asks that speaker again and
+ * keeps the answers before it. With later speakers already answered, the
+ * person picks: keep them, or ask them again from here. The old answer
+ * stays as a version ("< 1/2 >").
+ * - #200: the round follows the order of the group list, a member can sit
+ * out the next round, and "Skip speaker" ends one turn while the round
+ * goes on ("Stop round" still ends all of it).
+ *
+ * Driven through the real `useChat()` with only the network replaced: what
+ * is asserted is who was asked, and what the chat holds afterwards.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+
+vi.mock('../../api/cloud/supabase', () => ({ getAccessToken: async () => 'session-token-abc' }))
+vi.mock('../../lib/ttsBridge', () => ({ autoSpeak: () => {} }))
+vi.mock('../../api/vram-handoff', () => ({ requestGenerationCancel: () => {} }))
+vi.mock('../useMemory', () => ({
+ useMemory: () => ({ extractAndSave: async () => {} }),
+ extractMemoriesFromPair: async () => {},
+}))
+vi.mock('../../lib/run-lane-of-model', () => ({
+ laneOf: () => 'cloud',
+ currentLaneFacts: () => ({ openaiSlotIsLocal: true, ollamaBaseIsLocal: true }),
+}))
+
+import { useChat } from '../useChat'
+import { useChatStore } from '../../stores/chatStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { useProviderStore } from '../../stores/providerStore'
+import { useGenerationStore } from '../../stores/generationStore'
+import { useGroupRoundStore, skipGroupSpeaker } from '../../stores/groupRoundStore'
+import { __resetRunLanesForTests } from '../../lib/run-lanes'
+import { forkMarks } from '../../lib/chat-forks'
+import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../../lib/constants'
+
+const A = 'openai::walt'
+const B = 'openai::baron'
+const C = 'openai::clara'
+
+interface Request { model: string }
+let requests: Request[] = []
+let calls: Record<string, number> = {}
+/** Models whose answer waits until the request is aborted. */
+let hang = new Set<string>()
+
+beforeEach(() => {
+ requests = []
+ calls = {}
+ hang = new Set()
+ __resetRunLanesForTests()
+ useChatStore.setState({ conversations: [], activeConversationId: null })
+ useGenerationStore.setState({ generating: {}, aborters: {}, runs: {} })
+ useGroupRoundStore.setState({ live: {} })
+ useModelStore.setState({ models: [], activeModel: A })
+ useSettingsStore.setState({
+ settings: { ...DEFAULT_SETTINGS, appMode: 'local', cavemanMode: 'off' },
+ personas: [...BUILT_IN_PERSONAS],
+ })
+ useProviderStore.setState((s) => ({
+ providers: { ...s.providers, openai: { ...s.providers.openai, enabled: true } },
+ }))
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
+ if (!String(input).includes('/chat/completions')) return new Response('{}', { status: 200 })
+ const body = JSON.parse(String((init as RequestInit).body)) as Request
+ requests.push(body)
+ calls[body.model] = (calls[body.model] ?? 0) + 1
+ if (hang.has(body.model)) {
+ const signal = (init as RequestInit).signal
+ await new Promise<never>((_, reject) => {
+ const fail = () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
+ if (signal?.aborted) fail()
+ signal?.addEventListener('abort', fail)
+ })
+ }
+ const text = `${body.model} ${calls[body.model]}`
+ return new Response(`data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\ndata: [DONE]\n\n`, {
+ status: 200, headers: { 'content-type': 'text/event-stream' },
+ })
+ })
+})
+afterEach(() => vi.restoreAllMocks())
+
+function openGroup(members = [A, B, C]): string {
+ const convId = useChatStore.getState().createConversation(A, '')
+ useChatStore.getState().setActiveConversation(convId)
+ useChatStore.getState().setGroupModels(convId, members)
+ return convId
+}
+
+const conv = (id: string) => useChatStore.getState().conversations.find((c) => c.id === id)!
+const said = (id: string) => conv(id).messages.filter((m) => m.role === 'assistant').map((m) => m.content)
+const asked = () => requests.map((r) => r.model)
+
+async function withChat<T>(fn: (chat: ReturnType<typeof useChat>) => Promise<T>): Promise<T> {
+ const { result } = renderHook(() => useChat())
+ let out!: T
+ await act(async () => { out = await fn(result.current) })
+ return out
+}
+
+describe('GH #199: regenerate one speaker', () => {
+ it('only the second speaker answers again; the first and the third are kept', async () => {
+ const id = openGroup()
+ await withChat((c) => c.sendMessage('go'))
+ expect(said(id)).toEqual(['walt 1', 'baron 1', 'clara 1'])
+ const second = conv(id).messages.find((m) => m.content === 'baron 1')!
+
+ requests = []
+ expect(await withChat((c) => c.regenerateSpeaker(id, second.id, 'only'))).toBe(true)
+ expect(asked()).toEqual(['baron'])
+ expect(said(id)).toEqual(['walt 1', 'baron 2', 'clara 1'])
+ // One user line, never a second copy of it.
+ expect(conv(id).messages.filter((m) => m.role === 'user').length).toBe(1)
+
+ // The old answer is a version, and "< 2/2 >" sits on the new one.
+ const fresh = conv(id).messages.find((m) => m.content === 'baron 2')!
+ const mark = forkMarks(conv(id)).get(fresh.id)!
+ expect(mark).toMatchObject({ index: 1, total: 2 })
+ useChatStore.getState().switchFork(id, mark.key, 0)
+ expect(said(id)).toEqual(['walt 1', 'baron 1', 'clara 1'])
+ // Every message lives in one place: the kept third answer is a copy.
+ useChatStore.getState().switchFork(id, mark.key, 1)
+ const ids = conv(id).messages.map((m) => m.id)
+ const oldVersion = conv(id).forks![mark.key].versions[0]!.map((m) => m.id)
+ expect(ids.filter((x) => oldVersion.includes(x))).toEqual([])
+ })
+
+ it('"from here" asks the speaker and everyone after it, in the round order', async () => {
+ const id = openGroup()
+ await withChat((c) => c.sendMessage('go'))
+ const second = conv(id).messages.find((m) => m.content === 'baron 1')!
+ requests = []
+ await withChat((c) => c.regenerateSpeaker(id, second.id, 'from-here'))
+ expect(asked()).toEqual(['baron', 'clara'])
+ expect(said(id)).toEqual(['walt 1', 'baron 2', 'clara 2'])
+ })
+
+ it('the last speaker regenerates alone, nothing later to ask about', async () => {
+ const id = openGroup()
+ await withChat((c) => c.sendMessage('go'))
+ const third = conv(id).messages.find((m) => m.content === 'clara 1')!
+ requests = []
+ await withChat((c) => c.regenerateSpeaker(id, third.id, 'only'))
+ expect(asked()).toEqual(['clara'])
+ expect(said(id)).toEqual(['walt 1', 'baron 1', 'clara 2'])
+ })
+
+ it('negative control: "Regenerate whole round" still asks everyone again', async () => {
+ const id = openGroup()
+ await withChat((c) => c.sendMessage('go'))
+ const second = conv(id).messages.find((m) => m.content === 'baron 1')!
+ requests = []
+ await withChat(async (c) => { c.regenerateMessage(id, second.id) })
+ await vi.waitFor(() => expect(said(id)).toEqual(['walt 2', 'baron 2', 'clara 2']))
+ expect(asked()).toEqual(['walt', 'baron', 'clara'])
+ })
+})
+
+describe('GH #200: order, who answers, skip', () => {
+ it('the round follows the order of the list', async () => {
+ const id = openGroup([C, A, B])
+ await withChat((c) => c.sendMessage('go'))
+ expect(asked()).toEqual(['clara', 'walt', 'baron'])
+ expect(said(id)).toEqual(['clara 1', 'walt 1', 'baron 1'])
+ })
+
+ it('a member set to sit out misses the next round only', async () => {
+ const id = openGroup()
+ useChatStore.getState().setGroupSitOut(id, [A, C])
+ await withChat((c) => c.sendMessage('only baron'))
+ expect(asked()).toEqual(['baron'])
+ expect(conv(id).groupSitOut).toBeUndefined()
+ await withChat((c) => c.sendMessage('everyone'))
+ expect(asked()).toEqual(['baron', 'walt', 'baron', 'clara'])
+ })
+
+ it('sitting everyone out is no pick: everyone answers', async () => {
+ const id = openGroup([A, B])
+ useChatStore.getState().setGroupSitOut(id, [A, B])
+ await withChat((c) => c.sendMessage('go'))
+ expect(asked()).toEqual(['walt', 'baron'])
+ })
+
+ it('"Skip speaker" ends the turn that runs and the next speaker answers', async () => {
+ const id = openGroup()
+ hang.add('walt')
+ const { result } = renderHook(() => useChat())
+ let round!: Promise<void>
+ act(() => { round = result.current.sendMessage('go') })
+ await vi.waitFor(() => expect(useGroupRoundStore.getState().live[id]).toMatchObject({ speaker: A, index: 0, total: 3 }))
+ await vi.waitFor(() => expect(asked()).toEqual(['walt']))
+ expect(skipGroupSpeaker(id)).toBe(true)
+ await act(async () => { await round })
+ expect(asked()).toEqual(['walt', 'baron', 'clara'])
+ // Skipped before a word: no empty bubble stands for it.
+ expect(said(id)).toEqual(['baron 1', 'clara 1'])
+ expect(useGroupRoundStore.getState().live[id]).toBeUndefined()
+ expect(skipGroupSpeaker(id)).toBe(false)
+ })
+
+ it('negative control: "Stop round" ends the round, nobody after answers', async () => {
+ const id = openGroup()
+ hang.add('walt')
+ const { result } = renderHook(() => useChat())
+ let round!: Promise<void>
+ act(() => { round = result.current.sendMessage('go') })
+ await vi.waitFor(() => expect(asked()).toEqual(['walt']))
+ act(() => { result.current.stopGeneration() })
+ await act(async () => { await round })
+ expect(asked()).toEqual(['walt'])
+ expect(useGroupRoundStore.getState().live[id]).toBeUndefined()
+ })
+})
diff --git a/src/hooks/__tests__/group-speaker-model-swap.test.ts b/src/hooks/__tests__/group-speaker-model-swap.test.ts
index 0fb43c7b..e9d32fe6 100644
--- a/src/hooks/__tests__/group-speaker-model-swap.test.ts
+++ b/src/hooks/__tests__/group-speaker-model-swap.test.ts
@@ -35,8 +35,10 @@ describe('every speaker gets its own model loaded', () => {
expect(groupRound).not.toMatch(/builtinReloadNeeded|ensureBuiltinEngineAlive/)
// The round still does nothing but hand each model its own turn, and the
// turn is where the model is loaded.
- expect(groupRound).toMatch(/for \(const model of models\)/)
- expect(groupRound).toMatch(/await runGroupTurn\(convId, model, models, abort\)/)
+ // (3.0.9, GH #200: each turn runs under a controller of its own, so a
+ // speaker can be skipped without ending the round.)
+ expect(groupRound).toMatch(/for \(const \[index, model\] of models\.entries\(\)\)/)
+ expect(groupRound).toMatch(/await runGroupTurn\(convId, model, table, turn\)/)
})
it('reloads BEFORE the provider call, not after', () => {
diff --git a/src/hooks/useABCompare.ts b/src/hooks/useABCompare.ts
index 799bd20b..2b78e18b 100644
--- a/src/hooks/useABCompare.ts
+++ b/src/hooks/useABCompare.ts
@@ -8,7 +8,7 @@ import { useCompareStore } from '../stores/compareStore'
import { useSettingsStore } from '../stores/settingsStore'
import { getProviderForModel, getProviderIdFromModel } from '../api/providers'
import { getChatWindowTokens } from '../lib/context-compaction'
-import { applySendBudget, chatBudgetApplies, sharedChatSendBudget } from '../lib/chat-send-budget'
+import { applySendBudget, chatBudgetApplies, chatBudgetHysteresis, sharedChatSendBudget } from '../lib/chat-send-budget'
import { sendsToALanBackend } from '../lib/lan-openai-slot'
import { buildChatSystemPrompt } from '../lib/system-prompt'
import { v4 as uuid } from 'uuid'
@@ -103,11 +103,18 @@ export function useABCompare() {
sendWindowTokens: sendWindowFor(settings, m),
contextDecay: settings.contextDecay,
localBackend: sendsToALanBackend(providerId, m),
+ answerTokens: settings.maxTokens,
}
}),
),
)
- const sendMessages = applySendBudget(chatMessages, budget).messages
+ // GH #201: two local sides are trimmed to their budget and no deeper, and
+ // the note they read is a conversation's, not an agent's.
+ const hysteresis = [modelA, modelB].some((m) => {
+ const id = getProviderIdFromModel(m)
+ return chatBudgetHysteresis({ providerId: id, localBackend: sendsToALanBackend(id, m) })
+ })
+ const sendMessages = applySendBudget(chatMessages, budget, { hysteresis, notice: 'chat' }).messages
// R5-10/R5-11: Compare has no conversation of its own (compareStore, not
// chatStore), so there is no per-chat override to read; only the "omit a
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 9315aaf5..82aab23f 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -28,7 +28,7 @@ import { isSearchStopped, waitForSlotOrStop } from "../lib/slot-wait"
import { sourcesFromChunks } from "../lib/rag-sources"
import { buildRagSuffix, RETRIEVAL_FAILED_MESSAGE } from "../lib/rag-prompt"
import { buildTurnContext, withTurnContext } from "../lib/turn-context"
-import { getChatWindowTokens, capMessageCount, compactMessages, estimateMessageTokens } from "../lib/context-compaction"
+import { getChatWindowTokens, capMessageCount, compactMessages, compactMessagesWithCount, estimateMessageTokens } from "../lib/context-compaction"
import { contextOverflowOf, shrunkSendWindow } from "./codex/context-overflow"
import { applyChatSendBudget, chatBudgetApplies, sendBudgetWouldTrim } from "../lib/chat-send-budget"
import { sendsToALanBackend } from "../lib/lan-openai-slot"
@@ -66,6 +66,9 @@ import { fileMessageFields, filesWithoutWorkspace, type ChatFileInput } from "..
import { fitFilesForSend, requestTextOf } from "./chat-file-room"
import { isGroupChat, availableGroupMembers, groupSystemPrompt, groupHistory, groupSpeakers, stripImpersonatedSpeakers, hasGroupHistory, soloSpeakers, soloTurnAuthorFields, soloHistoryTag, SOLO_HISTORY_LINE } from "../lib/group-chat"
import { explainSendRefusal } from "../lib/template-refusal"
+import { laterAnswersInRound, nextRoundSpeakers, regenerateSpeakers, copiesForNewVersion } from "../lib/group-rounds"
+import { groupTurnStarted, groupRoundEnded } from "../stores/groupRoundStore"
+import { forkStart } from "../lib/chat-forks"
import { builtinReloadNeeded, ensureBuiltinEngineAlive } from "../api/builtin-ensure"
import { emptyAnswerExplanation } from "../lib/answer-notes"
import { beginModelSwitchWatch, cutByModelSwitch, finishReasonAfterSwitch, MODEL_SWITCH_FINISH } from "../lib/model-switch-stop"
@@ -188,26 +191,40 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
// GH #181: each member carries the reminder of the persona it plays, in
// its own request only, by the same rule as its prompt and its sampling.
const note = personaNoteOf(speakerPersonaFor(conv, model, personas, activePersonaId, true))
- const messages = applyChatSendBudget(
- capMessageCount([
- { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt, speakers) },
- ...groupHistory(conv.messages, model, speakers, { groupPersonas: conv.groupPersonas, personas }),
- ]),
- {
- note,
- providerId,
- // Only asked where the answer can change something — which, since the
- // notaus is now the only thing that closes the gate, means: unless the
- // user switched capping off. The lookup is cached per model, so a group
- // round does not pay an /api/show per member per turn.
- modelWindow: chatBudgetApplies(providerId, settings.contextDecay)
- ? await getChatWindowTokens(model)
- : 0,
- sendWindowTokens: sendWindowFor(settings, model),
- contextDecay: settings.contextDecay,
- localBackend: sendsToALanBackend(providerId, model),
- },
- ).messages
+ // Only asked where the answer can change something — which, since the
+ // notaus is now the only thing that closes the gate, means: unless the
+ // user switched capping off. The lookup is cached per model, so a group
+ // round does not pay an /api/show per member per turn.
+ //
+ // GH #201: the window is THIS speaker's, as picked for its model, and a
+ // local speaker's budget is that window less the answer's room
+ // (chatSendBudget). It used to end at 0.56 of the window: 128K-131K of a
+ // 256K pick, every round.
+ const modelWindow = chatBudgetApplies(providerId, settings.contextDecay)
+ ? await getChatWindowTokens(model)
+ : 0
+ const full = [
+ { role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt, speakers) },
+ ...groupHistory(conv.messages, model, speakers, { groupPersonas: conv.groupPersonas, personas }),
+ ]
+ const counted = capMessageCount([...full])
+ const sent = applyChatSendBudget(counted, {
+ note,
+ providerId,
+ modelWindow,
+ sendWindowTokens: sendWindowFor(settings, model),
+ contextDecay: settings.contextDecay,
+ localBackend: sendsToALanBackend(providerId, model),
+ answerTokens: settings.maxTokens,
+ notice: 'chat',
+ })
+ let messages = sent.messages
+ // Said in the chat, next to this answer: older turns did not go out.
+ let dropped = full.length - counted.length + sent.droppedMessages
+ const noteTrim = () => useChatStore.getState().updateMessageHistoryTrim(
+ convId, assistantMessage.id, dropped > 0 ? { dropped, window: modelWindow } : null,
+ )
+ noteTrim()
const canThink = isThinkingCompatible(model)
const useThinking: boolean | undefined = canThink ? settings.thinkingEnabled === true : undefined
@@ -261,12 +278,35 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
// GH #175: each member runs on the values of its own persona, the chat's
// own Sampling values on top. Not gated on the Personas switch, the same
// rule as the member's prompt above.
- const stream = provider.chatStream(modelId, messages, {
+ const streamOpts = {
...speakerSamplingOptions(settings, conv, model, personas, activePersonaId, true),
- window: 'chat',
+ window: 'chat' as const,
thinking: useThinking,
signal: abort.signal,
- })
+ }
+ // The same one retry as plain chat: the engine refused the prompt as
+ // larger than its context, because its own count ran ahead of the
+ // estimate. Cut once under what it named and send again; the refusal
+ // comes before any token, so nothing shows twice.
+ async function* streamWithOverflowRetry() {
+ try {
+ yield* provider.chatStream(modelId, messages, streamOpts)
+ } catch (err) {
+ const overflow = contextOverflowOf(err)
+ if (!overflow) throw err
+ type Wire = Parameters<typeof estimateMessageTokens>[0]
+ const size = estimateMessageTokens(messages as unknown as Wire)
+ const next = shrunkSendWindow(size, overflow, size)
+ const cut = next !== null ? compactMessagesWithCount(messages as unknown as Wire, next, { notice: 'chat' }) : null
+ if (!cut || cut.messages.length >= messages.length) throw err
+ log.info('chat.group_context_overflow_retry', { sent: size, next, window: overflow.window, promptTokens: overflow.promptTokens, kept: cut.messages.length })
+ messages = cut.messages as unknown as typeof messages
+ dropped += cut.dropped
+ noteTrim()
+ yield* provider.chatStream(modelId, messages, streamOpts)
+ }
+ }
+ const stream = streamWithOverflowRetry()
for await (const chunk of stream) {
if (abort.signal.aborted) break
@@ -423,6 +463,14 @@ interface ChatRun {
*/
const activeChatRuns = new Map<string, symbol>()
+/** A group round that answers again instead of starting from a new user
+ * line (GH #199): who speaks, and what to do once the round holds its
+ * claim, before the first speaker (move the old answers into a version). */
+interface GroupRoundAgain {
+ speakers: string[]
+ prepare: () => void
+}
+
/**
* "A send of this conversation is on its way", from the tap to the end.
*
@@ -547,7 +595,7 @@ export function useChat() {
* a second local conversation could stream from the built-in engine at the
* same time, silently, because `localLaneHolder()` never heard about the
* group round at all. */
- const runGroupRound = useCallback(async (convId: string, content: string, images: ImageAttachment[] | undefined, members: string[], files?: ChatFileInput[]) => {
+ const runGroupRound = useCallback(async (convId: string, content: string, images: ImageAttachment[] | undefined, members: string[], files?: ChatFileInput[], again?: GroupRoundAgain): Promise<boolean> => {
// Auflage 3 (Review composer, 19.09.2026): derselbe Wiedereintritts-Riegel
// wie sendMessage oben ("Re-entry guard"). Ohne ihn ueberschrieb ein
// doppeltes Enter auf einem Gruppenchat den Token der ersten Runde weiter
@@ -558,7 +606,7 @@ export function useChat() {
// Verlauf. Claim synchron, vor der ersten Nachricht, exakt wie dort.
if (activeChatRuns.has(convId)) {
log.info('chat.duplicate_group_round_blocked', { convId })
- return
+ return false
}
const myRunToken = Symbol(convId)
activeChatRuns.set(convId, myRunToken)
@@ -582,37 +630,51 @@ export function useChat() {
// shown as unavailable in the group menu, and speaks again once its
// model is listed again.
const listed = useModelStore.getState()
- const models = availableGroupMembers(members, listed.models, listed.inventoryLoaded)
-
- // GH #171: an attached text goes out whole when it fits, and as far as
- // it fits otherwise. One user line reaches every speaker, so it is
- // fitted to the smallest window at the table (all members when none is
- // listed: then nobody answers and the size does not matter).
- const sendFiles = await fitFilesForSend({
- files: filesWithoutWorkspace(files),
- models: models.length ? models : members,
- use: 'chat',
- otherText: requestTextOf(useChatStore.getState().conversations.find((c) => c.id === convId), content),
- })
- useChatStore.getState().addMessage(convId, {
- id: uuid(),
- role: 'user',
- // An attached file reaches every speaker as its summary, inside the
- // one user line they all share (lib/chat-files.ts).
- ...fileMessageFields(content, sendFiles),
- images,
- timestamp: Date.now(),
- })
-
- if (models.length === 0) {
+ // Everyone at the table: named to each speaker and tagged in its history.
+ const table = availableGroupMembers(members, listed.models, listed.inventoryLoaded)
+ // Who answers THIS round. A regenerate (GH #199) names its speakers and
+ // adds no user line; a new round takes the group's order less whoever
+ // was set to sit it out (GH #200), and that pick is used up here.
+ let models: string[]
+ if (again) {
+ models = again.speakers.filter((m) => table.includes(m))
+ if (models.length === 0) return false
+ again.prepare()
+ } else {
+ const sitOut = useChatStore.getState().conversations.find((c) => c.id === convId)?.groupSitOut
+ models = nextRoundSpeakers(table, sitOut)
+ if (sitOut?.length) useChatStore.getState().setGroupSitOut(convId, [])
+
+ // GH #171: an attached text goes out whole when it fits, and as far as
+ // it fits otherwise. One user line reaches every speaker, so it is
+ // fitted to the smallest window at the table (all members when none is
+ // listed: then nobody answers and the size does not matter).
+ const sendFiles = await fitFilesForSend({
+ files: filesWithoutWorkspace(files),
+ models: models.length ? models : members,
+ use: 'chat',
+ otherText: requestTextOf(useChatStore.getState().conversations.find((c) => c.id === convId), content),
+ })
useChatStore.getState().addMessage(convId, {
id: uuid(),
- role: 'system',
- notice: 'info',
- content: 'No model of this group is in the model list right now, so nobody answered. Load one of them again, or change the group under Plugins.',
+ role: 'user',
+ // An attached file reaches every speaker as its summary, inside the
+ // one user line they all share (lib/chat-files.ts).
+ ...fileMessageFields(content, sendFiles),
+ images,
timestamp: Date.now(),
})
- return
+
+ if (models.length === 0) {
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(),
+ role: 'system',
+ notice: 'info',
+ content: 'No model of this group is in the model list right now, so nobody answered. Load one of them again, or change the group under Plugins.',
+ timestamp: Date.now(),
+ })
+ return true
+ }
}
// The round holds the lane its SPEAKERS need. Mixed local+cloud speakers
@@ -643,11 +705,33 @@ export function useChat() {
setIsGenerating(true)
useGenerationStore.getState().setGenerating(convId, true)
try {
- for (const model of models) {
+ for (const [index, model] of models.entries()) {
if (abort.signal.aborted) break
- await runGroupTurn(convId, model, models, abort)
+ // Each turn has a controller of its own under the round's: Stop
+ // ends the round, "Skip speaker" (GH #200) ends this turn only and
+ // the next speaker takes over.
+ const turn = new AbortController()
+ const endTurn = () => turn.abort()
+ abort.signal.addEventListener('abort', endTurn)
+ groupTurnStarted(convId, { speaker: model, index, total: models.length }, endTurn)
+ const before = useChatStore.getState().conversations.find((c) => c.id === convId)?.messages.length ?? 0
+ try {
+ await runGroupTurn(convId, model, table, turn)
+ } finally {
+ abort.signal.removeEventListener('abort', endTurn)
+ }
+ if (turn.signal.aborted && !abort.signal.aborted) {
+ // Skipped before a word: no empty bubble is left standing for it.
+ // What it had written stays, as with Stop.
+ const said = useChatStore.getState().conversations.find((c) => c.id === convId)?.messages[before]
+ if (said?.role === 'assistant' && said.modelId === model && !said.content.trim()) {
+ useChatStore.getState().deleteMessage(convId, said.id)
+ }
+ log.info('chat.group_speaker_skipped', { convId, index })
+ }
}
} finally {
+ groupRoundEnded(convId)
// Same identity check as the single-model turn below (Blocker 2,
// review-lanes.md): a Stop followed by an immediate resend on this
// conversation can register a new aborter before this round's
@@ -692,6 +776,7 @@ export function useChat() {
// Eintrag muss deshalb hier freigegeben werden.
activeChatRuns.delete(convId)
}
+ return true
} finally {
if (activeChatRuns.get(convId) === myRunToken) {
activeChatRuns.delete(convId)
@@ -953,7 +1038,8 @@ export function useChat() {
{
const groupConv = store.conversations.find((c) => c.id === store.activeConversationId)
if (groupConv && isGroupChat(groupConv.groupModels)) {
- return runGroupRound(groupConv.id, content, images, groupConv.groupModels, files)
+ await runGroupRound(groupConv.id, content, images, groupConv.groupModels, files)
+ return
}
}
@@ -1376,6 +1462,7 @@ export function useChat() {
sendWindowTokens: sendWindowFor(settings, activeModel),
contextDecay: settings.contextDecay,
localBackend: sendsToALanBackend(providerId, activeModel),
+ answerTokens: settings.maxTokens,
},
)
await maybeAutoCompact({
@@ -1482,6 +1569,13 @@ export function useChat() {
// eigenen Netz stellt keine Rechnung; jeder andere Sendepfad gibt es
// schon mit (useAgentChat, useCodex, useABCompare, run-compact-command).
localBackend: sendsToALanBackend(providerId, activeModel),
+ answerTokens: settings.maxTokens,
+ notice: 'chat',
+ // GH #201: older turns that did not go out are said next to the answer.
+ onTrimmed: (dropped) => useChatStore.getState().updateMessageHistoryTrim(convId, assistantMessage.id, {
+ dropped,
+ window: modelWindowTokens,
+ }),
},
).messages
// Phone only: the request ends with the cut answer instead of the
@@ -1652,7 +1746,7 @@ export function useChat() {
const sent = estimateMessageTokens(messages as unknown as Wire)
const next = shrunkSendWindow(sent, overflow, sent)
const cut = next !== null
- ? (compactMessages(messages as unknown as Wire, next) as unknown as typeof messages)
+ ? (compactMessages(messages as unknown as Wire, next, { notice: 'chat' }) as unknown as typeof messages)
: messages
if (cut === messages || cut.length >= messages.length) throw err
log.info('chat.context_overflow_retry', { sent, next, window: overflow.window, promptTokens: overflow.promptTokens, kept: cut.length })
@@ -2206,6 +2300,51 @@ export function useChat() {
resend(conversationId, assistantMessageId)
}, [resend])
+ /**
+ * GH #199: one speaker of a group round answers again, and only that
+ * speaker ('only'), or it and every speaker after it in the round
+ * ('from-here'). The answers before it stay as they are.
+ *
+ * The old answer is not lost: it moves into a version like every
+ * regenerate since GH #172, and "< 1/2 >" sits on the new answer. With
+ * 'only', the later answers of the round come back after the new one, as
+ * copies, so each version holds its own. Regenerating the whole round is
+ * still `regenerateMessage`.
+ *
+ * Resolves false when nothing ran (another run in flight, no such speaker
+ * at the table any more) or nothing was written; the version shown before
+ * comes back then.
+ */
+ const regenerateSpeaker = useCallback(async (conversationId: string, messageId: string, mode: 'only' | 'from-here'): Promise<boolean> => {
+ if (activeChatRuns.has(conversationId)) return false
+ const conv = useChatStore.getState().conversations.find((c) => c.id === conversationId)
+ if (!conv || !isGroupChat(conv.groupModels)) return false
+ const listed = useModelStore.getState()
+ const table = availableGroupMembers(conv.groupModels, listed.models, listed.inventoryLoaded)
+ const speakers = regenerateSpeakers(conv.messages, messageId, mode, table)
+ if (speakers.length === 0) return false
+ const kept = mode === 'only' ? laterAnswersInRound(conv.messages, messageId) : []
+ const fork = { key: null as string | null }
+ const ran = await runGroupRound(conversationId, '', undefined, conv.groupModels, undefined, {
+ speakers,
+ prepare: () => { fork.key = useChatStore.getState().forkFrom(conversationId, messageId) },
+ })
+ const key = fork.key
+ if (!ran || key === null) return false
+ const store = useChatStore.getState()
+ const now = store.conversations.find((c) => c.id === conversationId)
+ if (!now) return true
+ const start = forkStart(now.messages, key)
+ const fresh = start < 0 ? [] : now.messages.slice(start)
+ if (fresh.every((m) => m.role === 'assistant' && !m.content.trim())) {
+ for (const m of fresh) store.deleteMessage(conversationId, m.id)
+ store.restoreEmptyFork(conversationId, key)
+ return false
+ }
+ for (const m of copiesForNewVersion(kept, uuid)) store.addMessage(conversationId, m)
+ return true
+ }, [runGroupRound])
+
const editAndResend = useCallback((conversationId: string, messageId: string, newContent: string): boolean => {
return resend(conversationId, messageId, newContent)
}, [resend])
@@ -2216,6 +2355,7 @@ export function useChat() {
isGenerating: isGenerating || agentChat.isAgentRunning || orphanRun,
isLoadingModel,
regenerateMessage,
+ regenerateSpeaker,
editAndResend,
// Agent mode additions
isAgentRunning: agentChat.isAgentRunning,
diff --git a/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts b/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts
index 2451ba8a..03197119 100644
--- a/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts
+++ b/src/lib/__tests__/a-lan-server-is-not-a-bill.test.ts
@@ -31,7 +31,7 @@ const { useProviderStore } = await import('../../stores/providerStore')
const { effectiveSendWindow, isPaidProvider, DEFAULT_SEND_WINDOW_TOKENS, WINDOW_SHARE } =
await import('../send-window')
const { isLanOpenAiBackend, sendsToALanBackend } = await import('../lan-openai-slot')
-const { chatSendBudget } = await import('../chat-send-budget')
+const { chatSendBudget, chatAnswerReserve } = await import('../chat-send-budget')
const LOCAL_MODEL_WINDOW = 262144
@@ -127,7 +127,9 @@ describe('the budget follows it', () => {
modelWindow: LOCAL_MODEL_WINDOW,
localBackend: sendsToALanBackend('openai', null),
})
- expect(local).toBe(Math.floor(LOCAL_MODEL_WINDOW * WINDOW_SHARE))
+ // GH #201: a conversation on a local server keeps its window less the
+ // answer's room, not 0.8 of it.
+ expect(local).toBe(LOCAL_MODEL_WINDOW - chatAnswerReserve(LOCAL_MODEL_WINDOW))
slotPointsAt('https://api.openai.com/v1', false)
expect(
@@ -217,7 +219,8 @@ describe('no budget is computed without asking the question', () => {
/**
* Und was das am Hauptpfad in Tokens ausmacht. Der eigene Server im Netz
- * stellt keine Rechnung, also gilt dort 0.8 mal das eigene Fenster und nicht
+ * stellt keine Rechnung, also gilt dort das eigene Fenster weniger dem
+ * Platz fuer die Antwort (GH #201, vorher 0.8 mal das Fenster) und nicht
* die Kostendeckelung fuer bezahlte Anbieter.
*/
it('a LAN server in the openai slot keeps its own window on the main path', () => {
@@ -228,7 +231,7 @@ describe('no budget is computed without asking the question', () => {
modelWindow: 262_144,
localBackend: sendsToALanBackend('openai', null),
}),
- ).toBe(209_715)
+ ).toBe(262_144 - 8192)
slotPointsAt('https://api.openai.com/v1', false)
expect(
diff --git a/src/lib/__tests__/chat-send-budget.test.ts b/src/lib/__tests__/chat-send-budget.test.ts
index 33313169..7a3d2ecf 100644
--- a/src/lib/__tests__/chat-send-budget.test.ts
+++ b/src/lib/__tests__/chat-send-budget.test.ts
@@ -51,8 +51,10 @@ const CLOUD_262K = { providerId: 'lu-cloud', modelWindow: 262144, contextDecay:
const OLLAMA = { providerId: 'ollama', modelWindow: 262144, contextDecay: true }
/** Ein lokales Modell mit einem Fenster, das eine lange Unterhaltung sprengt. */
const OLLAMA_8K = { providerId: 'ollama', modelWindow: 8192, contextDecay: true }
-/** Die Grenze, ab der die A3-Hysterese auf einem lokalen Modell greift. */
-const TRIGGER_8K = Math.floor(Math.floor(8192 * 0.8) * 1.15)
+/** GH #201: ein lokales Modell wird an seinem Fenster weniger dem Platz
+ * fuer die Antwort gemessen (8 Prozent, 512 bis 8192), ohne Hysterese. */
+const TRIGGER_8K = 8192 - Math.floor(8192 * 0.08)
+const BUDGET_262K = 262144 - 8192
describe('A4: a long chat costs budget level, not history level', () => {
it('a 50k-token history plus a short question sends at most the budget', () => {
@@ -126,9 +128,10 @@ describe('2.6.8: ein lokales Modell wird gekappt — aber erst, wo es ueberlaeuf
const history = historyOf(50000)
expect(size(history)).toBeGreaterThan(TRIGGER_8K)
const sent = applyChatSendBudget(history, OLLAMA_8K)
- expect(sent.budget).toBe(Math.floor(8192 * 0.8))
+ expect(sent.budget).toBe(TRIGGER_8K)
expect(sent.promptTokens).toBeLessThanOrEqual(sent.budget!)
expect(sent.messages.length).toBeLessThan(history.length)
+ expect(sent.droppedMessages).toBeGreaterThan(0)
})
// Negativkontrolle in der Zeit: derselbe Fall war vor diesem Umbau
@@ -140,9 +143,8 @@ describe('2.6.8: ein lokales Modell wird gekappt — aber erst, wo es ueberlaeuf
expect(sent.messages).toBe(history)
})
- // Die Zahl, die der Modulkopf von chat-send-budget.ts behauptet: nicht bei
- // 0,8 des Fensters, sondern bei 1,15 x 0,8 = 0,92 — der Rest ist der Platz,
- // den die ANTWORT braucht.
+ // Bis 100K bleibt die Grenze, wo die Hysterese sie hatte (0,92 des
+ // Fensters); der Rest ist der Platz, den die ANTWORT braucht.
it('die Grenze liegt bei 92 Prozent des Fensters, nicht bei 80', () => {
expect(TRIGGER_8K / 8192).toBeCloseTo(0.92, 2)
const knappDrunter = historyOf(TRIGGER_8K - 800)
@@ -177,7 +179,7 @@ describe('2.6.8: ein lokales Modell wird gekappt — aber erst, wo es ueberlaeuf
// codexSendWindowTokens gedeckelt, der lokale nur auf sein eigenes
// Fenster. Das ist der Unterschied, den `isPaidProvider` weiter macht.
expect(chatSendBudget({ providerId: 'ollama', modelWindow: 262144, contextDecay: true }))
- .toBe(Math.floor(262144 * 0.8))
+ .toBe(BUDGET_262K)
expect(chatSendBudget(CLOUD_262K)).toBe(DEFAULT_SEND_WINDOW_TOKENS)
})
})
@@ -197,11 +199,11 @@ describe('A4: a group round is budgeted per model per round', () => {
// sie ungekappt an beide.
const shared = historyOf(120000)
const sent = applyChatSendBudget(shared, OLLAMA_8K)
- expect(sent.budget).toBe(Math.floor(8192 * 0.8))
+ expect(sent.budget).toBe(TRIGGER_8K)
expect(sent.promptTokens).toBeLessThanOrEqual(sent.budget!)
// Und das grosse lokale Modell derselben Runde behaelt ein Vielfaches
// davon. Was seine Nutzlast begrenzt, ist nicht die neue Token-Decke
- // (209715 waere sie), sondern MAX_SEND_MESSAGES — die aeltere Anzahl-Decke,
+ // (253952 waere sie), sondern MAX_SEND_MESSAGES — die aeltere Anzahl-Decke,
// die diese Historie mit ihren ~480 kurzen Zuegen schon vorher traf.
const gross = applyChatSendBudget(shared, OLLAMA)
expect(gross.promptTokens).toBeGreaterThan(sent.promptTokens * 10)
@@ -239,8 +241,8 @@ describe('A4: compare caps the shared base before the fan-out', () => {
it('zwei lokale Modelle teilen sich das engere ihrer Fenster', () => {
// Beide Seiten muessen denselben Prompt sehen, sonst ist der Vergleich
// keiner — also gilt auch unter lokalen Modellen das kleinere Fenster.
- expect(sharedChatSendBudget([OLLAMA, OLLAMA])).toBe(Math.floor(262144 * 0.8))
- expect(sharedChatSendBudget([OLLAMA, OLLAMA_8K])).toBe(Math.floor(8192 * 0.8))
+ expect(sharedChatSendBudget([OLLAMA, OLLAMA])).toBe(BUDGET_262K)
+ expect(sharedChatSendBudget([OLLAMA, OLLAMA_8K])).toBe(TRIGGER_8K)
// Mit dem Notaus auf beiden Seiten bleibt es beim ungekappten Array.
const aus = [OLLAMA, OLLAMA_8K].map((m) => ({ ...m, contextDecay: false }))
expect(sharedChatSendBudget(aus)).toBeNull()
diff --git a/src/lib/__tests__/group-chat.test.ts b/src/lib/__tests__/group-chat.test.ts
index dacd2c82..0c1523bd 100644
--- a/src/lib/__tests__/group-chat.test.ts
+++ b/src/lib/__tests__/group-chat.test.ts
@@ -144,8 +144,10 @@ describe('wiring (source guards)', () => {
it('every group turn is labeled and one abort spans the whole round', () => {
expect(useChatSrc).toContain('modelId: model')
- expect(useChatSrc).toContain('await runGroupTurn(convId, model, models, abort)')
+ expect(useChatSrc).toContain('await runGroupTurn(convId, model, table, turn)')
expect(useChatSrc).toContain('if (abort.signal.aborted) break')
+ // The turn's controller follows the round's: Stop still ends the round.
+ expect(useChatSrc).toContain("abort.signal.addEventListener('abort', endTurn)")
})
it('the bubble names the speaker only when a turn carries a model', () => {
diff --git a/src/lib/__tests__/group-rounds.test.ts b/src/lib/__tests__/group-rounds.test.ts
new file mode 100644
index 00000000..33f852a2
--- /dev/null
+++ b/src/lib/__tests__/group-rounds.test.ts
@@ -0,0 +1,72 @@
+/**
+ * 3.0.9, GH #199, #200: the shape of a group round, as pure functions.
+ * Run: npx vitest run src/lib/__tests__/group-rounds.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { copiesForNewVersion, hasLaterRounds, isSpeakerTurn, laterAnswersInRound, moveMember, nextRoundSpeakers, regenerateSpeakers } from '../group-rounds'
+import type { Message } from '../../types/chat'
+
+const m = (id: string, role: Message['role'], modelId?: string, extra: Partial<Message> = {}): Message =>
+ ({ id, role, content: id, timestamp: 0, ...(modelId ? { modelId } : {}), ...extra })
+
+const thread: Message[] = [
+ m('u1', 'user'),
+ m('a1', 'assistant', 'A'),
+ m('n1', 'system', undefined, { notice: 'info' }),
+ m('b1', 'assistant', 'B'),
+ m('h1', 'user', undefined, { hidden: true }),
+ m('c1', 'assistant', 'C'),
+ m('u2', 'user'),
+ m('a2', 'assistant', 'A'),
+]
+
+describe('a round', () => {
+ it('runs to the next visible user line; notices and hidden lines are not speakers', () => {
+ expect(laterAnswersInRound(thread, 'a1').map((x) => x.id)).toEqual(['b1', 'c1'])
+ expect(laterAnswersInRound(thread, 'c1')).toEqual([])
+ expect(laterAnswersInRound(thread, 'missing')).toEqual([])
+ })
+
+ it('knows when later rounds follow', () => {
+ expect(hasLaterRounds(thread, 'b1')).toBe(true)
+ expect(hasLaterRounds(thread, 'a2')).toBe(false)
+ })
+
+ it('a speaker turn is an answer with its model after a user line', () => {
+ expect(isSpeakerTurn(thread, 'b1')).toBe(true)
+ expect(isSpeakerTurn(thread, 'u1')).toBe(false)
+ expect(isSpeakerTurn([m('g', 'assistant', 'A')], 'g')).toBe(false)
+ })
+})
+
+describe('GH #199: who answers again', () => {
+ it("'only' is that speaker, 'from-here' it and the later ones in their order", () => {
+ expect(regenerateSpeakers(thread, 'a1', 'only', ['A', 'B', 'C'])).toEqual(['A'])
+ expect(regenerateSpeakers(thread, 'a1', 'from-here', ['A', 'B', 'C'])).toEqual(['A', 'B', 'C'])
+ })
+
+ it('a member no longer at the table sits it out', () => {
+ expect(regenerateSpeakers(thread, 'a1', 'from-here', ['A', 'C'])).toEqual(['A', 'C'])
+ expect(regenerateSpeakers(thread, 'b1', 'only', ['A', 'C'])).toEqual([])
+ })
+
+ it('kept answers come back as copies with ids of their own', () => {
+ let n = 0
+ const copies = copiesForNewVersion([m('b1', 'assistant', 'B', { historyTrim: { dropped: 3, window: 8192 } })], () => `new${++n}`)
+ expect(copies).toEqual([{ id: 'new1', role: 'assistant', content: 'b1', timestamp: 0, modelId: 'B' }])
+ })
+})
+
+describe('GH #200: order and who answers', () => {
+ it('moves a member', () => {
+ expect(moveMember(['A', 'B', 'C'], 2, 0)).toEqual(['C', 'A', 'B'])
+ expect(moveMember(['A', 'B', 'C'], 0, 1)).toEqual(['B', 'A', 'C'])
+ expect(moveMember(['A', 'B'], 0, 5)).toEqual(['A', 'B'])
+ })
+
+ it('the next round is the order less who sits out, never nobody', () => {
+ expect(nextRoundSpeakers(['A', 'B', 'C'], undefined)).toEqual(['A', 'B', 'C'])
+ expect(nextRoundSpeakers(['A', 'B', 'C'], ['B'])).toEqual(['A', 'C'])
+ expect(nextRoundSpeakers(['A', 'B'], ['A', 'B'])).toEqual(['A', 'B'])
+ })
+})
diff --git a/src/lib/__tests__/history-trim-note.test.ts b/src/lib/__tests__/history-trim-note.test.ts
new file mode 100644
index 00000000..0394ea54
--- /dev/null
+++ b/src/lib/__tests__/history-trim-note.test.ts
@@ -0,0 +1,15 @@
+/** GH #201: the line next to an answer whose request left older turns out. */
+import { describe, it, expect } from 'vitest'
+import { historyTrimNote } from '../history-trim-note'
+
+describe('historyTrimNote', () => {
+ it('names the count, the speaker and the window, in chat words', () => {
+ expect(historyTrimNote({ dropped: 12, window: 262144 }, 'Baron'))
+ .toBe('12 earlier messages were not sent to Baron: they no longer fit its 256K context. The chat itself keeps them.')
+ expect(historyTrimNote({ dropped: 1, window: 8192 }))
+ .toBe('1 earlier message was not sent: it no longer fits its 8K context. The chat itself keeps it.')
+ })
+ it('never an agent word', () => {
+ expect(historyTrimNote({ dropped: 3, window: 0 })).not.toMatch(/task|file|re-read/)
+ })
+})
diff --git a/src/lib/chat-send-budget.ts b/src/lib/chat-send-budget.ts
index 54b26bb4..1e69e5ed 100644
--- a/src/lib/chat-send-budget.ts
+++ b/src/lib/chat-send-budget.ts
@@ -23,9 +23,9 @@
* budget while the count climbs past the proxy's 400-message gate.
*/
-import { COMPACT_TRIGGER_RATIO, compactMessages, estimateMessageTokens } from './context-compaction'
+import { COMPACT_TRIGGER_RATIO, compactMessagesWithCount, estimateMessageTokens } from './context-compaction'
import { ageOutImages } from './context-images'
-import { effectiveSendWindow } from './send-window'
+import { effectiveSendWindow, isPaidProvider } from './send-window'
import { injectPersonaNote, noteTokens, type PersonaNote } from './persona-note'
export interface ChatSendBudgetInput {
@@ -40,6 +40,51 @@ export interface ChatSendBudgetInput {
/** Whether this payload goes to a machine on this network. See
* lib/lan-openai-slot; a LAN server in the `openai` slot is not a bill. */
localBackend?: boolean
+ /** settings.maxTokens: the answer length the user set, 0 or absent = auto.
+ * A local conversation keeps exactly this much of its window free for the
+ * answer (GH #201), see chatAnswerReserve. */
+ answerTokens?: number
+}
+
+/** What a local conversation keeps free for the answer when no answer length
+ * is set: 8 percent of the window, at least 512 and at most 8192 tokens. */
+export const CHAT_ANSWER_RESERVE_SHARE = 0.08
+export const CHAT_ANSWER_RESERVE_MIN = 512
+export const CHAT_ANSWER_RESERVE_MAX = 8192
+
+/**
+ * The part of a LOCAL model's window a conversation keeps free for the answer
+ * (GH #201). num_ctx covers prompt plus completion, so a prompt filled to the
+ * brim leaves no room to reply.
+ *
+ * The answer length the user set, else 8 percent of the window between 512
+ * and 8192 tokens; never more than a quarter of the window. Up to a 100K
+ * window that is where the trim engaged before (0.92 of the window), so a
+ * small model is trimmed no earlier than it was. Above it the room stops
+ * growing with the window: a 256K pick keeps 8K free instead of 52K.
+ */
+export function chatAnswerReserve(window: number, answerTokens?: number): number {
+ const quarter = Math.floor(window / 4)
+ const want = typeof answerTokens === 'number' && answerTokens > 0
+ ? Math.floor(answerTokens)
+ : Math.min(CHAT_ANSWER_RESERVE_MAX, Math.max(CHAT_ANSWER_RESERVE_MIN, Math.floor(window * CHAT_ANSWER_RESERVE_SHARE)))
+ return Math.max(1, Math.min(want, quarter))
+}
+
+/**
+ * Whether a conversation payload to this provider is trimmed with the A3
+ * hysteresis (wait for 1.15 x budget, then drop to 0.7 x budget).
+ *
+ * GH #201: only a paid one. The hysteresis is a cache argument for a billed
+ * prefix, and on a chat it never even held the prefix still: the stored
+ * conversation is always the full one, so once it was over the trigger EVERY
+ * send dropped to 0.7 x 0.8 = 0.56 of the window. A 256K local model in a
+ * group chat sent about 128K-131K tokens, round after round, and told the
+ * model an agent's "re-read that file". A local chat is trimmed to its budget
+ * and no further.
+ */
+export function chatBudgetHysteresis(input: Pick<ChatSendBudgetInput, 'providerId' | 'localBackend'>): boolean {
+ return isPaidProvider(input.providerId, input.localBackend)
}
/**
@@ -110,6 +155,13 @@ export function chatBudgetApplies(_providerId: string, contextDecay?: boolean):
*/
export function chatSendBudget(input: ChatSendBudgetInput): number | null {
if (!chatBudgetApplies(input.providerId, input.contextDecay)) return null
+ // GH #201: a local model's budget is the window the user picked for it,
+ // less the answer's room. It used to be 0.8 of the window, which on 256K
+ // held back 52K tokens of history for an answer of a few thousand.
+ if (!isPaidProvider(input.providerId, input.localBackend)) {
+ const w = Number.isFinite(input.modelWindow) && input.modelWindow > 0 ? Math.floor(input.modelWindow) : 0
+ return w > 0 ? w - chatAnswerReserve(w, input.answerTokens) : null
+ }
const window = effectiveSendWindow({
providerId: input.providerId,
modelWindow: input.modelWindow,
@@ -140,6 +192,8 @@ export interface ChatSendResult<T> {
promptTokens: number
/** Attachments left behind by the image rule. */
droppedImages: number
+ /** Older messages the token budget left out of this payload (GH #201). */
+ droppedMessages: number
}
export interface ApplyBudgetOptions {
@@ -147,6 +201,13 @@ export interface ApplyBudgetOptions {
keepImages?: number
/** GH #181: the speaker's persona reminder (lib/persona-note.ts). */
note?: PersonaNote | null
+ /** The A3 hysteresis, on unless said otherwise. A local conversation
+ * turns it off (chatBudgetHysteresis, GH #201). */
+ hysteresis?: boolean
+ /** Who reads the trim notice: an agent run (default) or a conversation. */
+ notice?: 'agent' | 'chat'
+ /** Told how many older messages the budget left out, when it left any. */
+ onTrimmed?: (dropped: number) => void
}
/**
@@ -172,17 +233,22 @@ export function applySendBudget<T extends { role: string; content?: unknown }>(
budget: null,
promptTokens: estimateMessageTokens(messages as unknown as Estimated),
droppedImages: 0,
+ droppedMessages: 0,
}
}
const aged = ageOutImages(messages, { keepRecent: opts.keepImages })
- const compacted = compactMessages(aged.messages as unknown as Estimated, budget, {
- hysteresis: true,
- }) as unknown as T[]
+ const compacted = compactMessagesWithCount(aged.messages as unknown as Estimated, budget, {
+ hysteresis: opts.hysteresis !== false,
+ notice: opts.notice,
+ })
+ const out = compacted.messages as unknown as T[]
+ if (compacted.dropped > 0) opts.onTrimmed?.(compacted.dropped)
return {
- messages: compacted,
+ messages: out,
budget,
- promptTokens: estimateMessageTokens(compacted as unknown as Estimated),
+ promptTokens: estimateMessageTokens(out as unknown as Estimated),
droppedImages: aged.strippedImages,
+ droppedMessages: compacted.dropped,
}
}
@@ -201,9 +267,15 @@ export function applyChatSendBudget<T extends { role: string; content?: unknown
): ChatSendResult<T> {
const budget = chatSendBudget(input)
const note = input.note ?? null
- if (!note) return applySendBudget(messages, budget, { keepImages: input.keepImages })
+ const how = {
+ keepImages: input.keepImages,
+ hysteresis: input.hysteresis ?? chatBudgetHysteresis(input),
+ notice: input.notice,
+ onTrimmed: input.onTrimmed,
+ }
+ if (!note) return applySendBudget(messages, budget, how)
const reserved = budget !== null ? Math.max(1, budget - noteTokens(note)) : null
- const sent = applySendBudget(messages, reserved, { keepImages: input.keepImages })
+ const sent = applySendBudget(messages, reserved, how)
const out = injectPersonaNote(sent.messages, note)
return {
...sent,
@@ -231,5 +303,5 @@ export function sendBudgetWouldTrim<T extends { role: string; content?: unknown
const note = input.note ?? null
const held = note ? Math.max(1, budget - noteTokens(note)) : budget
const used = estimateMessageTokens(messages as unknown as Parameters<typeof estimateMessageTokens>[0])
- return used > Math.floor(held * COMPACT_TRIGGER_RATIO)
+ return used > (chatBudgetHysteresis(input) ? Math.floor(held * COMPACT_TRIGGER_RATIO) : held)
}
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index d4fa39a8..aa582790 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -142,6 +142,9 @@ const COUNT_BUDGET = MAX_SEND_MESSAGES - 3
* any real instruction; a pasted 200 KB file does not ride along forever. */
const PINNED_TASK_MAX_CHARS = 8000
+/** The agent notice without its trail of done calls, to size its room. */
+const AGENT_NOTICE_SIZE_PROBE = '[999 earlier messages were trimmed to fit the context window. The original task still stands. Results you already saw still hold. If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]'
+
/** How many already-done tool names the trim notice carries. */
const DONE_TRAIL_MAX = 40
@@ -175,7 +178,17 @@ function toolNamesIn(msg: OllamaChatMessage): string[] {
* shared /g regex carries lastIndex state between .test and .replace calls.
*/
const trimNoticeRe = () =>
- /\s*\[\d+ earlier messages? (?:was|were) trimmed to fit the context window\.[^\]]*\]\s*/g
+ /\s*\[(?:\d+ earlier messages? (?:was|were) trimmed to fit the context window\.|Note: \d+ earlier messages? of this conversation (?:is|are) not included here)[^\]]*\]\s*/g
+
+/**
+ * The trim notice for a CONVERSATION (GH #201): plain chat, a group round,
+ * compare. The agent's wording below talks about a task, results and files to
+ * re-read, which in a story only confuses the model. This one says what is
+ * true in a chat: the start is missing, carry on from what is here.
+ */
+export function chatTrimNotice(dropped: number): string {
+ return `[Note: ${dropped} earlier message${dropped === 1 ? ' of this conversation is' : 's of this conversation are'} not included here because they no longer fit the context window. Continue naturally from the messages you can see.]`
+}
/** Remove an earlier trim notice from a message body, so repeated compaction
* rounds never stack notices inside the pinned task or the kept window. */
@@ -325,6 +338,9 @@ export const COMPACT_DROP_BLOCK = 16
export interface CompactOptions {
/** Wait for budget × 1.15, then drop to budget × 0.7. */
hysteresis?: boolean
+ /** Who reads the trim notice: an agent run (default) or a conversation,
+ * which gets chatTrimNotice (GH #201). */
+ notice?: 'agent' | 'chat'
}
export function compactMessages(
@@ -332,13 +348,27 @@ export function compactMessages(
maxTokens: number,
opts: CompactOptions = {},
): OllamaChatMessage[] {
+ return compactMessagesWithCount(messages, maxTokens, opts).messages
+}
+
+/**
+ * compactMessages, and how many of the older messages it left out. The count
+ * is what the chat shows under an answer whose request was trimmed (GH #201),
+ * so nobody has to guess from a token counter that turns were dropped.
+ */
+export function compactMessagesWithCount(
+ messages: OllamaChatMessage[],
+ maxTokens: number,
+ opts: CompactOptions = {},
+): { messages: OllamaChatMessage[]; dropped: number } {
+ const unchanged = { messages, dropped: 0 }
const currentTokens = estimateMessageTokens(messages)
const triggerTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TRIGGER_RATIO) : maxTokens
const targetTokens = opts.hysteresis ? Math.floor(maxTokens * COMPACT_TARGET_RATIO) : maxTokens
// Already within budget — BOTH budgets. A history that fits the token
// window but exceeds the message-count ceiling still has to shrink.
- if (currentTokens <= triggerTokens && messages.length <= MAX_SEND_MESSAGES) return messages
+ if (currentTokens <= triggerTokens && messages.length <= MAX_SEND_MESSAGES) return unchanged
// Separate system prompt (always kept). A stray system message deeper in
// the history that is only an old trim notice is dropped outright here:
@@ -351,7 +381,7 @@ export function compactMessages(
)
// If we have fewer messages than KEEP_RECENT, can't compact further
- if (nonSystem.length <= KEEP_RECENT) return messages
+ if (nonSystem.length <= KEEP_RECENT) return unchanged
const systemTokens = systemMsg ? estimateMessageTokens([systemMsg]) : 0
const budget = Math.max(0, targetTokens - systemTokens)
@@ -400,7 +430,11 @@ export function compactMessages(
// Accumulate a recent suffix that fits, newest-first. Keep at least
// KEEP_RECENT messages even when that exceeds budget (recent context is the
// most valuable), otherwise stop as soon as the next message would overflow.
- const suffixBudget = Math.max(0, budget - pinnedTokens)
+ // The trim notice rides on top of the window, so its room comes off first.
+ // Without the hysteresis (a local chat, GH #201) nothing else leaves slack
+ // under the budget, and the notice alone pushed the payload past it.
+ const noticeTokens = estimateTokens(opts.notice === 'chat' ? chatTrimNotice(999) : AGENT_NOTICE_SIZE_PROBE) + 8
+ const suffixBudget = Math.max(0, budget - pinnedTokens - noticeTokens)
const kept: OllamaChatMessage[] = []
let used = 0
for (let i = capped.length - 1; i >= 0; i--) {
@@ -426,7 +460,9 @@ export function compactMessages(
const droppedCount = capped.length - kept.length - (pinNeeded ? 1 : 0)
let notice: string | null = null
- if (droppedCount > 0) {
+ if (droppedCount > 0 && opts.notice === 'chat') {
+ notice = chatTrimNotice(droppedCount)
+ } else if (droppedCount > 0) {
// What was dropped is exactly the record of the work already done, while
// the pin keeps the instruction alive forever. Measured on the installed
// build 2026-08-06, Coding + Ollama + hermes, a 30 step plan: the run
@@ -458,11 +494,14 @@ export function compactMessages(
// between the pin and the window. Why that is forbidden, and where it goes
// instead, is now documented once at attachNoteToUserMaterial above — the
// written summary of 2.6.8 obeys the identical rule through the same call.
- return attachNoteToUserMaterial<OllamaChatMessage>({
- system: systemMsg,
- pinned: pinNeeded ? pinnedTask : null,
- kept,
- note: notice,
- strip: stripTrimNotice,
- })
+ return {
+ messages: attachNoteToUserMaterial<OllamaChatMessage>({
+ system: systemMsg,
+ pinned: pinNeeded ? pinnedTask : null,
+ kept,
+ note: notice,
+ strip: stripTrimNotice,
+ }),
+ dropped: Math.max(0, droppedCount),
+ }
}
diff --git a/src/lib/group-rounds.ts b/src/lib/group-rounds.ts
new file mode 100644
index 00000000..6dd94e9d
--- /dev/null
+++ b/src/lib/group-rounds.ts
@@ -0,0 +1,104 @@
+// The shape of one group round, and the choices a person makes about it
+// (3.0.9, GH #199 and GH #200).
+//
+// A round is the user's line and the answers after it, up to the next user
+// line. The speakers of a round are those answers' models, in the order they
+// spoke. Pure functions only: the hook runs the turns, the store keeps the
+// versions, the menu draws the order.
+import type { Message } from '../types/chat'
+
+const isAnswer = (m: Message): boolean => m.role === 'assistant' && !m.hidden
+
+/**
+ * The answers of the same round that come AFTER `messageId`, in order.
+ * Empty when it was the last speaker, when the next user line follows it,
+ * or when the message is not in the thread.
+ */
+export function laterAnswersInRound(messages: readonly Message[], messageId: string): Message[] {
+ const at = messages.findIndex((m) => m.id === messageId)
+ if (at < 0) return []
+ const out: Message[] = []
+ for (let i = at + 1; i < messages.length; i++) {
+ const m = messages[i]
+ if (m.role === 'user' && !m.hidden) break
+ if (isAnswer(m)) out.push(m)
+ }
+ return out
+}
+
+/** Whether a user line comes anywhere after `messageId`: a regenerate there
+ * takes the later rounds into the old version along with it. */
+export function hasLaterRounds(messages: readonly Message[], messageId: string): boolean {
+ const at = messages.findIndex((m) => m.id === messageId)
+ return at >= 0 && messages.slice(at + 1).some((m) => m.role === 'user' && !m.hidden)
+}
+
+/** Whether this answer is a group speaker's turn that can be regenerated on
+ * its own: an assistant answer with the model that wrote it, after a user
+ * line. */
+export function isSpeakerTurn(messages: readonly Message[], messageId: string): boolean {
+ const at = messages.findIndex((m) => m.id === messageId)
+ if (at < 0) return false
+ const m = messages[at]
+ if (!isAnswer(m) || !m.modelId) return false
+ return messages.slice(0, at).some((x) => x.role === 'user')
+}
+
+/**
+ * Who speaks when one answer is regenerated (GH #199).
+ *
+ * - 'only': that speaker alone; the later answers of the round are kept.
+ * - 'from-here': that speaker and every later one of the round, in the
+ * order they spoke, each answering again on what is said before it.
+ *
+ * Only speakers whose model is still at the table (`available`) are asked;
+ * one that left the list sits it out, as in a new round (GH #165).
+ */
+export function regenerateSpeakers(
+ messages: readonly Message[],
+ messageId: string,
+ mode: 'only' | 'from-here',
+ available: readonly string[],
+): string[] {
+ const target = messages.find((m) => m.id === messageId)
+ if (!target?.modelId) return []
+ const order = mode === 'only'
+ ? [target.modelId]
+ : [target.modelId, ...laterAnswersInRound(messages, messageId).map((m) => m.modelId).filter((x): x is string => !!x)]
+ return order.filter((m) => available.includes(m))
+}
+
+/**
+ * The members that answer the next round (GH #200): the group's order, less
+ * whoever the person set to sit this one out. A pick that would leave nobody
+ * is not a pick: everyone answers, as before.
+ */
+export function nextRoundSpeakers(members: readonly string[], sitOut: readonly string[] | undefined): string[] {
+ if (!sitOut?.length) return [...members]
+ const left = members.filter((m) => !sitOut.includes(m))
+ return left.length ? left : [...members]
+}
+
+/** The order after moving the member at `from` to `to` (drag and drop, or
+ * one step with the arrows). Out of range leaves the order as it was. */
+export function moveMember(members: readonly string[], from: number, to: number): string[] {
+ if (from < 0 || from >= members.length || to < 0 || to >= members.length || from === to) return [...members]
+ const next = [...members]
+ const [m] = next.splice(from, 1)
+ next.splice(to, 0, m)
+ return next
+}
+
+/**
+ * The later answers of a kept round, as copies for the new version (GH #199,
+ * "keep the later answers"). They stand in two versions then, the old one
+ * and the new one, and every message has to live in exactly one place
+ * (lib/chat-forks.ts), so the copies get ids of their own.
+ */
+export function copiesForNewVersion(answers: readonly Message[], newId: () => string): Message[] {
+ return answers.map((m) => {
+ const copy: Message = { ...m, id: newId() }
+ delete copy.historyTrim
+ return copy
+ })
+}
diff --git a/src/lib/history-trim-note.ts b/src/lib/history-trim-note.ts
new file mode 100644
index 00000000..bdd8a751
--- /dev/null
+++ b/src/lib/history-trim-note.ts
@@ -0,0 +1,13 @@
+// The line the chat shows next to an answer whose request left older turns
+// out (GH #201). Before 3.0.9 a trim was said only to the model, in an
+// agent's words, and the person found out from a token counter.
+import { formatContextWindow } from './formatters'
+
+/** "12 earlier messages were not sent to Baron: they no longer fit its 256K context." */
+export function historyTrimNote(trim: { dropped: number; window: number }, speaker?: string): string {
+ const what = trim.dropped === 1 ? '1 earlier message was' : `${trim.dropped} earlier messages were`
+ const who = speaker ? ` to ${speaker}` : ''
+ const fit = trim.window > 0 ? `its ${formatContextWindow(trim.window)} context` : 'its context'
+ const rest = trim.dropped === 1 ? `it no longer fits ${fit}. The chat itself keeps it.` : `they no longer fit ${fit}. The chat itself keeps them.`
+ return `${what} not sent${who}: ${rest}`
+}
diff --git a/src/stores/__tests__/settingsStore-context-picks-survive-update.test.ts b/src/stores/__tests__/settingsStore-context-picks-survive-update.test.ts
new file mode 100644
index 00000000..7c51660d
--- /dev/null
+++ b/src/stores/__tests__/settingsStore-context-picks-survive-update.test.ts
@@ -0,0 +1,92 @@
+/**
+ * GH #201: "the saved context picks of both models had fallen back to Auto"
+ * after an update. A pick made in the context menu is the user's word about
+ * their hardware and must ride every update untouched: the Ollama num_ctx
+ * (contextWindowOverride), the per model picks of LM Studio and of a custom
+ * server (contextWindowByModel), the LU Engine's ctx and the cloud send
+ * windows.
+ *
+ * (The loss reported for 3.0.6 to 3.0.7 was the move of LM Studio's pick out
+ * of the shared Ollama number into its own key, GH #168, which on purpose
+ * carried nothing over. Since then the key is stable, and this file holds
+ * every profile shape an update can meet to it.)
+ *
+ * Driven black-box: seed a versioned blob, fresh-import the store, read what
+ * the user gets, write it back and load it once more, as the next start does.
+ *
+ * Run: npx vitest run src/stores/__tests__/settingsStore-context-picks-survive-update.test.ts
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+
+const backing = new Map<string, string>()
+const localStorageShim = {
+ getItem: (k: string) => backing.get(k) ?? null,
+ setItem: (k: string, v: string) => void backing.set(k, String(v)),
+ removeItem: (k: string) => void backing.delete(k),
+ clear: () => backing.clear(),
+ key: (i: number) => [...backing.keys()][i] ?? null,
+ get length() {
+ return backing.size
+ },
+} as Storage
+
+const KEY = 'chat-settings'
+
+const PICKS = {
+ contextWindowOverride: 262144,
+ contextWindowByModel: {
+ 'lmstudio|gemma-4-31b-it-2': 262144,
+ 'http://192.168.1.20:5001/v1|gemma-4-31B-it-UD-Q8_K_XL': 262144,
+ },
+ cloudSendWindowByModel: { 'lu-cloud::qwen3.6-plus': 131072 },
+ builtinEngine: { ctx: 65536, ctxChosen: true },
+}
+
+function seed(settings: Record<string, unknown>, version: number) {
+ backing.set(KEY, JSON.stringify({
+ state: { settings, personas: [], activePersonaId: 'unrestricted', _version: version },
+ version,
+ }))
+}
+
+async function freshStore() {
+ vi.resetModules()
+ vi.stubGlobal('window', globalThis)
+ vi.stubGlobal('localStorage', localStorageShim)
+ const mod = await import('../settingsStore')
+ return mod.useSettingsStore
+}
+
+function expectPicks(s: Record<string, unknown>) {
+ expect(s.contextWindowOverride).toBe(262144)
+ expect(s.contextWindowByModel).toEqual(PICKS.contextWindowByModel)
+ expect(s.cloudSendWindowByModel).toEqual(PICKS.cloudSendWindowByModel)
+ expect((s.builtinEngine as { ctx: number; ctxChosen: boolean }).ctx).toBe(65536)
+ expect((s.builtinEngine as { ctx: number; ctxChosen: boolean }).ctxChosen).toBe(true)
+}
+
+describe('GH #201: the context picks survive an update', () => {
+ beforeEach(() => backing.clear())
+ afterEach(() => vi.unstubAllGlobals())
+
+ // 21: 2.6.7, 22: 2.6.8 to 3.0.6, 23: 3.0.7 and 3.0.8 (the current version,
+ // where zustand skips migrate and only onRehydrateStorage runs).
+ for (const version of [21, 22, 23]) {
+ it(`a profile written at store version ${version} keeps every pick`, async () => {
+ seed({ ...PICKS, temperature: 0.7 }, version)
+ const store = await freshStore()
+ expectPicks(store.getState().settings as unknown as Record<string, unknown>)
+
+ // The next start reads what this one wrote.
+ store.getState().updateSettings({ temperature: 0.71 })
+ const again = await freshStore()
+ expectPicks(again.getState().settings as unknown as Record<string, unknown>)
+ })
+ }
+
+ it('a fresh install starts on Auto everywhere, so the tests above prove a kept value', async () => {
+ const s = (await freshStore()).getState().settings
+ expect(s.contextWindowOverride).toBe(0)
+ expect(s.contextWindowByModel ?? {}).toEqual({})
+ })
+})
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 14581915..71a3d9ca 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -254,6 +254,9 @@ interface ChatState {
/** Group chat: the persona ONE participant speaks as in this chat, or
* `null` to let it follow the chat's own persona setting again. */
setGroupPersona: (id: string, model: string, personaId: string | null) => void
+ /** Group chat (GH #200): who sits out the next round. An empty list takes
+ * the pick away. */
+ setGroupSitOut: (id: string, models: string[]) => void
/** Write the model the open chat is actually running on.
*
* Befund 4 of the abnahme counter-check (2026-08-29): switching the model
@@ -280,6 +283,9 @@ interface ChatState {
/** The summed counts of one request (lib/request-usage.ts), replaced whole. */
updateMessageRequestUsage: (conversationId: string, messageId: string, requestUsage: RequestUsage) => void
updateMessageFinishReason: (conversationId: string, messageId: string, finishReason: string) => void
+ /** GH #201: how much older history the request behind this answer left
+ * out, or null when it went out whole. */
+ updateMessageHistoryTrim: (conversationId: string, messageId: string, trim: Message['historyTrim'] | null) => void
/** The kind of error a run ended with, or null to take it away again. */
updateMessageError: (conversationId: string, messageId: string, error: MessageError | null) => void
/** How long the model thought before it answered, in milliseconds. */
@@ -692,6 +698,22 @@ export const useChatStore = create<ChatState>()(
// persona stays their author once another model takes it over.
const leaving = Object.entries(c.groupPersonas ?? {}).filter(([model]) => !groupModels.includes(model))
if (leaving.length > 0) next.messages = stampGroupPersonas(c.messages, Object.fromEntries(leaving))
+ // GH #200: a member that left cannot sit out a round either.
+ const sitOut = (c.groupSitOut ?? []).filter((m) => groupModels.includes(m))
+ if (sitOut.length > 0) next.groupSitOut = sitOut
+ else delete next.groupSitOut
+ return next
+ }),
+ })),
+
+ setGroupSitOut: (id, models) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) => {
+ if (c.id !== id) return c
+ const sitOut = models.filter((m) => c.groupModels?.includes(m))
+ const next = { ...c }
+ if (sitOut.length > 0) next.groupSitOut = sitOut
+ else delete next.groupSitOut
return next
}),
})),
@@ -871,6 +893,24 @@ export const useChatStore = create<ChatState>()(
),
})),
+ updateMessageHistoryTrim: (conversationId, messageId, trim) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) => {
+ if (c.id !== conversationId) return c
+ return {
+ ...c,
+ messages: c.messages.map((m) => {
+ if (m.id !== messageId) return m
+ if (trim && trim.dropped > 0) return { ...m, historyTrim: trim }
+ if (!m.historyTrim) return m
+ const next = { ...m }
+ delete next.historyTrim
+ return next
+ }),
+ }
+ }),
+ })),
+
updateMessageError: (conversationId, messageId, error) =>
set((state) => ({
conversations: state.conversations.map((c) =>
diff --git a/src/stores/groupRoundStore.ts b/src/stores/groupRoundStore.ts
new file mode 100644
index 00000000..e57e201d
--- /dev/null
+++ b/src/stores/groupRoundStore.ts
@@ -0,0 +1,48 @@
+// Who is speaking in a running group round, and the one lever to move on
+// to the next speaker (3.0.9, GH #200).
+//
+// Before 3.0.7 a Stop during the first speaker started the second, which
+// people used to pick who answers. Since 3.0.7 Stop ends the round. Both are
+// wanted, so they are two actions now: "Skip speaker" ends only the turn that
+// runs, "Stop round" ends the round as Stop always has.
+//
+// Not persisted: a round lives as long as the app runs it.
+import { create } from 'zustand'
+
+export interface GroupRoundLive {
+ /** The model speaking now. */
+ speaker: string
+ /** Its place in this round, 0-based, and how many speak in it. */
+ index: number
+ total: number
+}
+
+export const useGroupRoundStore = create<{ live: Record<string, GroupRoundLive> }>(() => ({ live: {} }))
+
+const skippers = new Map<string, () => void>()
+
+/** The round of `convId` has moved on to `live.speaker`; `skip` ends that turn only. */
+export function groupTurnStarted(convId: string, live: GroupRoundLive, skip: () => void): void {
+ skippers.set(convId, skip)
+ useGroupRoundStore.setState((s) => ({ live: { ...s.live, [convId]: live } }))
+}
+
+/** The round of `convId` is over. */
+export function groupRoundEnded(convId: string): void {
+ skippers.delete(convId)
+ useGroupRoundStore.setState((s) => {
+ if (!(convId in s.live)) return s
+ const { [convId]: _gone, ...rest } = s.live
+ void _gone
+ return { live: rest }
+ })
+}
+
+/** "Skip speaker": end the turn that runs and go on with the next speaker.
+ * False when no round of this chat is running. */
+export function skipGroupSpeaker(convId: string): boolean {
+ const skip = skippers.get(convId)
+ if (!skip) return false
+ skip()
+ return true
+}
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 480e70fb..41a899b5 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -134,6 +134,10 @@ export interface Message {
* gets a persona stamped on later, so turning group chat back on does not
* hand it to whichever persona that model plays then. */
noGroupPersona?: true
+ /** GH #201: the request behind this answer left out `dropped` older
+ * messages to fit `window` tokens. The chat says so next to the answer.
+ * Absent when the whole conversation went out. */
+ historyTrim?: { dropped: number; window: number }
timestamp: number
images?: ImageAttachment[]
/** Files attached to this user message. `content` already carries their
@@ -286,6 +290,10 @@ export interface Conversation {
* follows the chat's own persona setting, which is how every group worked
* before this field existed. */
groupPersonas?: Record<string, string>
+ /** Group chat (GH #200): members set to sit out the NEXT round only. The
+ * round that starts takes it away again, so it never lingers. Absent:
+ * everyone answers, in the order of `groupModels`. */
+ groupSitOut?: string[]
/**
* Compactions that have happened in this chat, oldest first. The payload
* carries the newest merged state and any plain links after it; a chat from