Skip to content

Commit 96b9943

Browse files
rubimpassosgithub-actions[bot]
authored andcommitted
feat(chat): answer question prompts orphaned by OpenCode server restart
When the OpenCode server restarts while a question tool call is waiting, the pending request only lived in server memory and is destroyed (upstream anomalyco/opencode#36347), leaving the chat stuck with no answerable card. Detect question tool parts stranded pending/running in the last message of an idle session and re-render them as answerable QuestionCards: submitting re-checks the server first (question.reply when still pending) and otherwise delivers the answers as a new user message using the asking assistant message's model/agent. Ported from the `custom` branch across 1612 upstream commits. Three things changed on the way: Upstream now has its own question recovery (sync/question-recovery.ts), which retries fetching a question the server STILL holds. This covers the opposite case, a question the server no longer has, so the two sit side by side in ChatContainer. collectOrphanedQuestionRequests already skips any call id present in the live pending set, so a successful recovery wins and no orphan card appears. QuestionCard renders inside the virtualized timeline now, so no caller can hand it an `orphaned` prop. It defaults to the `orphaned:` id prefix that collectOrphanedQuestionRequests stamps on, which keeps both call sites and any future one correct without threading a prop through every list row. The effect that nudged layout through handleMessageContentChange was dropped: that callback no longer exists, and the virtualized list reflows on data change by itself. Tests for answerOrphanedQuestion are not yet ported; orphanedQuestions.ts keeps its own suite.
1 parent c9786c3 commit 96b9943

15 files changed

Lines changed: 569 additions & 6 deletions

File tree

‎packages/ui/src/components/chat/ChatContainer.tsx‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ const TIMELINE_SETTLE_CAP_MS = 300;
3838
import { PermissionCard } from './PermissionCard';
3939
import { QuestionCard } from './QuestionCard';
4040
import { hasActiveQuestionToolInCurrentTurn, recoverPendingQuestionWithRetry } from '@/sync/question-recovery';
41+
import { collectOrphanedQuestionRequests } from '@/lib/questions/orphanedQuestions';
4142
import { StatusRowContainer } from './StatusRowContainer';
4243
import { SessionRecapNote } from '@/components/chat/SessionRecapSpacer';
4344
import { SessionErrorNotice } from '@/components/chat/SessionErrorNotice';
@@ -90,6 +91,7 @@ import { createFirstVisibleSessionPerformanceTracker } from '@/sync/session-load
9091
import { isChatDirectoryPath } from '@/lib/chatDirectories';
9192

9293
const EMPTY_MESSAGES: Array<{ info: Message; parts: Part[] }> = [];
94+
const EMPTY_QUESTION_REQUESTS: QuestionRequest[] = [];
9395
const IDLE_SESSION_STATUS = { type: 'idle' as const };
9496
const CHAT_FORCE_SCROLL_BOTTOM_EVENT = 'openchamber:chat-force-scroll-bottom';
9597
const DEFAULT_RETRY_MESSAGE = 'Quota limit reached. Retrying automatically.';
@@ -882,6 +884,24 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({
882884
};
883885
}, [active, currentSessionId, effectiveSessionDirectory, hasUnreconciledQuestionTool, sync]);
884886

887+
// Questions destroyed by an OpenCode server restart: the question tool
888+
// part is stuck pending/running in the last message while the session is
889+
// idle and no live question exists. The retry above recovers a question the
890+
// server still holds; this covers the one it no longer has. Rendered as
891+
// answerable cards whose submission falls back to answer-as-message (see
892+
// orphanedQuestions.ts).
893+
const orphanedQuestions = React.useMemo(() => {
894+
if (!currentSessionId || sessionStatusForCurrent.type !== 'idle') {
895+
return EMPTY_QUESTION_REQUESTS;
896+
}
897+
const orphaned = collectOrphanedQuestionRequests(currentSessionId, sessionMessages, sessionQuestions);
898+
return orphaned.length > 0 ? orphaned : EMPTY_QUESTION_REQUESTS;
899+
}, [currentSessionId, sessionMessages, sessionQuestions, sessionStatusForCurrent.type]);
900+
const renderableQuestions = React.useMemo(() => {
901+
if (orphanedQuestions.length === 0) return sessionQuestions;
902+
return [...sessionQuestions, ...orphanedQuestions];
903+
}, [orphanedQuestions, sessionQuestions]);
904+
885905
const sessionIsWorking = React.useMemo(() => {
886906
if (!currentSessionId || sessionPermissions.length > 0 || sessionQuestions.length > 0) {
887907
return false;
@@ -1615,7 +1635,7 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({
16151635
endPinningReleased={userOwnsScroll}
16161636
revealWaited={revealWaited}
16171637
revealGate={revealGate}
1618-
sessionQuestions={sessionQuestions}
1638+
sessionQuestions={renderableQuestions}
16191639
sessionPermissions={sessionPermissions}
16201640
isProgrammaticFollowActive={isFollowingProgrammatically}
16211641
showLoadOlderButton={showLoadOlderButton}

‎packages/ui/src/components/chat/QuestionCard.tsx‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,26 @@ import { useUIStore } from '@/stores/useUIStore';
1212
import { useSessionUIStore } from '@/sync/session-ui-store';
1313
import { useSessions } from '@/sync/sync-context';
1414
import * as sessionActions from '@/sync/session-actions';
15+
import { isOrphanedQuestionId, markOrphanedQuestionDismissed } from '@/lib/questions/orphanedQuestions';
1516
import { useI18n } from '@/lib/i18n';
1617
import { serializeQuestionAsJson, serializeQuestionAsMarkdown } from './questionSerializers';
1718
import { QUESTION_CUSTOM_TEXTAREA_MIN_HEIGHT, getQuestionCustomTextareaHeight } from './questionTextareaSizing';
1819
import { QuestionMarkdown } from './QuestionMarkdown';
1920

2021
interface QuestionCardProps {
2122
question: QuestionRequest;
23+
/**
24+
* The question's pending request was destroyed by an OpenCode server
25+
* restart. Confirming routes through `answerOrphanedQuestion` (reply if the
26+
* server still knows the question, otherwise answer-as-message); dismissing
27+
* only hides the card locally.
28+
*
29+
* Defaults to the id prefix `collectOrphanedQuestionRequests` stamps on, so
30+
* the card stays correct wherever it renders: it sits inside the virtualized
31+
* timeline, and threading a prop down to it would have to cross every list
32+
* row.
33+
*/
34+
orphaned?: boolean;
2235
}
2336

2437
type TabKey = string;
@@ -88,7 +101,7 @@ const CustomAnswerTextarea = React.memo(function CustomAnswerTextarea({
88101
);
89102
});
90103

91-
export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
104+
export const QuestionCard: React.FC<QuestionCardProps> = ({ question, orphaned = isOrphanedQuestionId(question.id) }) => {
92105
const { t } = useI18n();
93106
const respondToQuestion = sessionActions.respondToQuestion;
94107
const rejectQuestion = sessionActions.rejectQuestion;
@@ -248,10 +261,14 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
248261
setIsResponding(true);
249262
try {
250263
const answers = buildAnswersPayload();
251-
await respondToQuestion(question.sessionID, question.id, answers);
264+
if (orphaned) {
265+
await sessionActions.answerOrphanedQuestion(question, answers);
266+
} else {
267+
await respondToQuestion(question.sessionID, question.id, answers);
268+
}
252269
setHasResponded(true);
253270
} catch (error) {
254-
if (sessionActions.isQuestionRequestNotFoundError(error)) {
271+
if (!orphaned && sessionActions.isQuestionRequestNotFoundError(error)) {
255272
toast.info(t('chat.questionCard.noLongerPending'));
256273
setHasResponded(true);
257274
} else {
@@ -262,7 +279,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
262279
} finally {
263280
setIsResponding(false);
264281
}
265-
}, [buildAnswersPayload, question.id, question.sessionID, requiredSatisfied, respondToQuestion, t]);
282+
}, [buildAnswersPayload, orphaned, question, requiredSatisfied, respondToQuestion, t]);
266283

267284
const handleKeyDown = React.useCallback(
268285
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -281,6 +298,13 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
281298
);
282299

283300
const handleDismiss = React.useCallback(async () => {
301+
if (orphaned) {
302+
if (question.tool?.callID) {
303+
markOrphanedQuestionDismissed(question.tool.callID);
304+
}
305+
setHasResponded(true);
306+
return;
307+
}
284308
setIsResponding(true);
285309
try {
286310
await rejectQuestion(question.sessionID, question.id);
@@ -297,7 +321,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
297321
} finally {
298322
setIsResponding(false);
299323
}
300-
}, [question.id, question.sessionID, rejectQuestion, t]);
324+
}, [orphaned, question.id, question.sessionID, question.tool?.callID, rejectQuestion, t]);
301325

302326
const handleCopyMarkdown = React.useCallback(async () => {
303327
const text = serializeQuestionAsMarkdown(question);
@@ -332,6 +356,11 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
332356
<div className="flex items-center gap-2">
333357
<Icon name="question" className="h-3.5 w-3.5 text-primary" />
334358
<span className="typography-meta font-medium text-muted-foreground">{t('chat.questionCard.inputNeeded')}</span>
359+
{orphaned ? (
360+
<span className="typography-micro px-1.5 py-0.5 rounded bg-[var(--status-warning-background)] text-[var(--status-warning)]">
361+
{t('chat.questionCard.orphanedBadge')}
362+
</span>
363+
) : null}
335364
{isFromSubagent ? (
336365
<span className="typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5">
337366
{t('chat.questionCard.fromSubagent')}
@@ -366,6 +395,11 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
366395
</div>
367396

368397
<div className="px-2 py-2">
398+
{orphaned ? (
399+
<div className="typography-micro text-muted-foreground mb-2">
400+
{t('chat.questionCard.orphanedNotice')}
401+
</div>
402+
) : null}
369403
{/* Minimal inline tabs for multiple questions */}
370404
{tabs.length > 1 ? (
371405
<div className="flex items-center gap-1 mb-2 flex-wrap">

‎packages/ui/src/lib/i18n/messages/en.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,6 +2337,8 @@ export const dict = {
23372337
'chat.questionCard.submitFailed': 'Failed to send response',
23382338
'chat.questionCard.dismissFailed': 'Failed to dismiss question',
23392339
'chat.questionCard.noLongerPending': 'This question is no longer waiting for a response.',
2340+
'chat.questionCard.orphanedBadge': 'Interrupted',
2341+
'chat.questionCard.orphanedNotice': 'The session restarted before this question was answered. Your answer will be sent to the agent as a new message.',
23402342
'chat.questionCard.tryAgain': 'Please try again in a moment.',
23412343
'chat.textSelection.toast.noProject': 'No project found for this session',
23422344
'chat.textSelection.toast.addToNotesFailed': 'Failed to add to notes',

‎packages/ui/src/lib/i18n/messages/es.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2315,6 +2315,8 @@ export const dict: Record<I18nKey, string> = {
23152315
"chat.questionCard.submitFailed": "No se pudo enviar la respuesta",
23162316
"chat.questionCard.dismissFailed": "No se pudo descartar la pregunta",
23172317
"chat.questionCard.noLongerPending": "Esta pregunta ya no espera una respuesta.",
2318+
"chat.questionCard.orphanedBadge": "Interrumpida",
2319+
"chat.questionCard.orphanedNotice": "La sesión se reinició antes de que esta pregunta fuera respondida. Tu respuesta se enviará al agente como un mensaje nuevo.",
23182320
"chat.questionCard.tryAgain": "Inténtalo de nuevo en un momento.",
23192321
"chat.textSelection.toast.noProject": "No se encontró proyecto para esta sesión",
23202322
"chat.textSelection.toast.addToNotesFailed": "No se pudo añadir a las notas",

‎packages/ui/src/lib/i18n/messages/fr.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3256,6 +3256,8 @@ export const dict = {
32563256
'chat.questionCard.submitFailed': 'Impossible d’envoyer la réponse',
32573257
'chat.questionCard.dismissFailed': 'Impossible d’ignorer la question',
32583258
'chat.questionCard.noLongerPending': 'Cette question n’attend plus de réponse.',
3259+
'chat.questionCard.orphanedBadge': 'Interrompue',
3260+
'chat.questionCard.orphanedNotice': 'La session a redémarré avant que cette question ne reçoive une réponse. Votre réponse sera envoyée à l’agent sous forme de nouveau message.',
32593261
'chat.questionCard.tryAgain': 'Veuillez réessayer dans un instant.',
32603262
'chat.messageBody.forkDialog.instructions.label': 'Instructions',
32613263
'chat.messageBody.forkDialog.instructions.placeholder': 'Ajouter des instructions pour la nouvelle session…',

‎packages/ui/src/lib/i18n/messages/ja.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2333,6 +2333,8 @@ export const dict: Record<I18nKey, string> = {
23332333
'chat.questionCard.submitFailed': '応答の送信に失敗しました',
23342334
'chat.questionCard.dismissFailed': '質問の閉じるのに失敗しました',
23352335
'chat.questionCard.noLongerPending': 'この質問は応答待ちではなくなりました。',
2336+
'chat.questionCard.orphanedBadge': '中断',
2337+
'chat.questionCard.orphanedNotice': 'この質問に回答する前にセッションが再起動されました。回答は新しいメッセージとしてエージェントに送信されます。',
23362338
'chat.questionCard.tryAgain': 'しばらくしてからもう一度お試しください。',
23372339
'chat.textSelection.toast.noProject': 'このセッションのプロジェクトが見つかりません',
23382340
'chat.textSelection.toast.addToNotesFailed': 'メモへの追加に失敗しました',

‎packages/ui/src/lib/i18n/messages/ko.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2339,6 +2339,8 @@ export const dict: Record<I18nKey, string> = {
23392339
'chat.questionCard.submitFailed': '응답 전송에 실패했습니다',
23402340
'chat.questionCard.dismissFailed': '질문 닫기에 실패했습니다',
23412341
'chat.questionCard.noLongerPending': '이 질문은 더 이상 응답을 기다리지 않습니다.',
2342+
'chat.questionCard.orphanedBadge': '중단됨',
2343+
'chat.questionCard.orphanedNotice': '이 질문에 답하기 전에 세션이 다시 시작되었습니다. 답변은 새 메시지로 에이전트에게 전송됩니다.',
23422344
'chat.questionCard.tryAgain': '잠시 후 다시 시도하세요.',
23432345
'chat.textSelection.toast.noProject': '이 세션의 프로젝트를 찾을 수 없음',
23442346
'chat.textSelection.toast.addToNotesFailed': '메모 추가 실패',

‎packages/ui/src/lib/i18n/messages/pl.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -962,6 +962,8 @@ export const dict: Record<I18nKey, string> = {
962962
'chat.questionCard.submitFailed': 'Nie udało się wysłać odpowiedzi',
963963
'chat.questionCard.dismissFailed': 'Nie udało się odrzucić pytania',
964964
'chat.questionCard.noLongerPending': 'To pytanie nie czeka już na odpowiedź.',
965+
'chat.questionCard.orphanedBadge': 'Przerwane',
966+
'chat.questionCard.orphanedNotice': 'Sesja została uruchomiona ponownie, zanim udzielono odpowiedzi na to pytanie. Twoja odpowiedź zostanie wysłana do agenta jako nowa wiadomość.',
965967
'chat.questionCard.tryAgain': 'Spróbuj ponownie za chwilę.',
966968
'chat.textSelection.toast.noProject': 'Nie znaleziono projektu dla tej sesji',
967969
'chat.textSelection.toast.addToNotesFailed': 'Nie udało się dodać do notatek',

‎packages/ui/src/lib/i18n/messages/pt-BR.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2317,6 +2317,8 @@ export const dict: Record<I18nKey, string> = {
23172317
"chat.questionCard.submitFailed": "Falha ao enviar a resposta",
23182318
"chat.questionCard.dismissFailed": "Falha ao descartar a pergunta",
23192319
"chat.questionCard.noLongerPending": "Esta pergunta não está mais aguardando uma resposta.",
2320+
"chat.questionCard.orphanedBadge": "Interrompida",
2321+
"chat.questionCard.orphanedNotice": "A sessão foi reiniciada antes desta pergunta ser respondida. Sua resposta será enviada ao agente como uma nova mensagem.",
23202322
"chat.questionCard.tryAgain": "Tente novamente em instantes.",
23212323
"chat.textSelection.toast.noProject": "Não foi encontrado projeto para esta sessão",
23222324
"chat.textSelection.toast.addToNotesFailed": "Não foi possível adicionar às notas",

‎packages/ui/src/lib/i18n/messages/uk.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2315,6 +2315,8 @@ export const dict: Record<I18nKey, string> = {
23152315
"chat.questionCard.submitFailed": "Не вдалося надіслати відповідь",
23162316
"chat.questionCard.dismissFailed": "Не вдалося відхилити питання",
23172317
"chat.questionCard.noLongerPending": "Це питання більше не очікує відповіді.",
2318+
"chat.questionCard.orphanedBadge": "Перервано",
2319+
"chat.questionCard.orphanedNotice": "Сесію було перезапущено до того, як на це питання відповіли. Вашу відповідь буде надіслано агенту як нове повідомлення.",
23182320
"chat.questionCard.tryAgain": "Спробуйте ще раз за мить.",
23192321
"chat.textSelection.toast.noProject": "Для цієї сесії не знайдено жодного проєкту",
23202322
"chat.textSelection.toast.addToNotesFailed": "Не вдалося додати до нотаток",

0 commit comments

Comments
 (0)