Skip to content

Commit 6c385f4

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.
1 parent 4b76d6e commit 6c385f4

16 files changed

Lines changed: 746 additions & 9 deletions

File tree

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

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { useGlobalSyncStore } from '@/sync/global-sync-store';
1313
import MessageList, { type MessageListHandle } from './MessageList';
1414
import { PermissionCard } from './PermissionCard';
1515
import { QuestionCard } from './QuestionCard';
16+
import { collectOrphanedQuestionRequests, isOrphanedQuestionId } from '@/lib/questions/orphanedQuestions';
1617
import { StatusRowContainer } from './StatusRowContainer';
1718
import { SessionRecapNote } from '@/components/chat/SessionRecapSpacer';
1819
import ScrollToBottomButton from './components/ScrollToBottomButton';
@@ -56,6 +57,7 @@ import { normalizeUserDisplayParts } from './message/normalizeUserDisplayParts';
5657
import { findShellCommandForMessage, isUserShellMarkerMessage } from './lib/shellBridge';
5758

5859
const EMPTY_MESSAGES: Array<{ info: Message; parts: Part[] }> = [];
60+
const EMPTY_QUESTION_REQUESTS: QuestionRequest[] = [];
5961
const IDLE_SESSION_STATUS = { type: 'idle' as const };
6062
const CHAT_FORCE_SCROLL_BOTTOM_EVENT = 'openchamber:chat-force-scroll-bottom';
6163
const DEFAULT_RETRY_MESSAGE = 'Quota limit reached. Retrying automatically.';
@@ -357,7 +359,7 @@ const ChatViewport = React.memo(({
357359
{(sessionQuestions.length > 0 || sessionPermissions.length > 0) && (
358360
<div>
359361
{sessionQuestions.map((question) => (
360-
<QuestionCard key={question.id} question={question} />
362+
<QuestionCard key={question.id} question={question} orphaned={isOrphanedQuestionId(question.id)} />
361363
))}
362364
{sessionPermissions.map((permission) => (
363365
<PermissionCard key={permission.id} permission={permission} />
@@ -581,6 +583,22 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
581583
const sessionPermissions = useScopedBlockingPermissions(currentSessionId, effectiveSessionDirectory);
582584
const sessionQuestions = useScopedBlockingQuestions(currentSessionId, effectiveSessionDirectory);
583585

586+
// Questions destroyed by an OpenCode server restart: the question tool
587+
// part is stuck pending/running in the last message while the session is
588+
// idle and no live question exists. Rendered as answerable cards whose
589+
// submission falls back to answer-as-message (see orphanedQuestions.ts).
590+
const orphanedQuestions = React.useMemo(() => {
591+
if (!currentSessionId || sessionStatusForCurrent.type !== 'idle') {
592+
return EMPTY_QUESTION_REQUESTS;
593+
}
594+
const orphaned = collectOrphanedQuestionRequests(currentSessionId, sessionMessages, sessionQuestions);
595+
return orphaned.length > 0 ? orphaned : EMPTY_QUESTION_REQUESTS;
596+
}, [currentSessionId, sessionMessages, sessionQuestions, sessionStatusForCurrent.type]);
597+
const renderableQuestions = React.useMemo(() => {
598+
if (orphanedQuestions.length === 0) return sessionQuestions;
599+
return [...sessionQuestions, ...orphanedQuestions];
600+
}, [orphanedQuestions, sessionQuestions]);
601+
584602
const sessionIsWorking = React.useMemo(() => {
585603
if (!currentSessionId || sessionPermissions.length > 0 || sessionQuestions.length > 0) {
586604
return false;
@@ -808,11 +826,11 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
808826
}, [timelineController.handleActiveTurnChange]);
809827

810828
React.useEffect(() => {
811-
if (sessionPermissions.length === 0 && sessionQuestions.length === 0) {
829+
if (sessionPermissions.length === 0 && renderableQuestions.length === 0) {
812830
return;
813831
}
814832
handleMessageContentChange('permission');
815-
}, [handleMessageContentChange, sessionPermissions, sessionQuestions]);
833+
}, [handleMessageContentChange, sessionPermissions, renderableQuestions]);
816834

817835
const navigation = useChatTurnNavigation({
818836
sessionId: currentSessionId,
@@ -1138,7 +1156,7 @@ export const ChatContainer: React.FC<ChatContainerProps> = ({ autoOpenDraft = tr
11381156
getAnimationHandlers={getAnimationHandlers}
11391157
handleHistoryScroll={timelineController.handleHistoryScroll}
11401158
scrollToBottom={resumeToLatestInstant}
1141-
sessionQuestions={sessionQuestions}
1159+
sessionQuestions={renderableQuestions}
11421160
sessionPermissions={sessionPermissions}
11431161
isProgrammaticFollowActive={isFollowingProgrammatically}
11441162
showLoadOlderButton={showLoadOlderButton}

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

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,20 @@ 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 { 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

1920
interface QuestionCardProps {
2021
question: QuestionRequest;
22+
/**
23+
* The question's pending request was destroyed by an OpenCode server
24+
* restart. Confirming routes through `answerOrphanedQuestion` (reply if the
25+
* server still knows the question, otherwise answer-as-message); dismissing
26+
* only hides the card locally.
27+
*/
28+
orphaned?: boolean;
2129
}
2230

2331
type TabKey = string;
@@ -87,7 +95,7 @@ const CustomAnswerTextarea = React.memo(function CustomAnswerTextarea({
8795
);
8896
});
8997

90-
export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
98+
export const QuestionCard: React.FC<QuestionCardProps> = ({ question, orphaned = false }) => {
9199
const { t } = useI18n();
92100
const respondToQuestion = sessionActions.respondToQuestion;
93101
const rejectQuestion = sessionActions.rejectQuestion;
@@ -247,10 +255,14 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
247255
setIsResponding(true);
248256
try {
249257
const answers = buildAnswersPayload();
250-
await respondToQuestion(question.sessionID, question.id, answers);
258+
if (orphaned) {
259+
await sessionActions.answerOrphanedQuestion(question, answers);
260+
} else {
261+
await respondToQuestion(question.sessionID, question.id, answers);
262+
}
251263
setHasResponded(true);
252264
} catch (error) {
253-
if (sessionActions.isQuestionRequestNotFoundError(error)) {
265+
if (!orphaned && sessionActions.isQuestionRequestNotFoundError(error)) {
254266
toast.info(t('chat.questionCard.noLongerPending'));
255267
setHasResponded(true);
256268
} else {
@@ -261,7 +273,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
261273
} finally {
262274
setIsResponding(false);
263275
}
264-
}, [buildAnswersPayload, question.id, question.sessionID, requiredSatisfied, respondToQuestion, t]);
276+
}, [buildAnswersPayload, orphaned, question, requiredSatisfied, respondToQuestion, t]);
265277

266278
const handleKeyDown = React.useCallback(
267279
(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -280,6 +292,13 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
280292
);
281293

282294
const handleDismiss = React.useCallback(async () => {
295+
if (orphaned) {
296+
if (question.tool?.callID) {
297+
markOrphanedQuestionDismissed(question.tool.callID);
298+
}
299+
setHasResponded(true);
300+
return;
301+
}
283302
setIsResponding(true);
284303
try {
285304
await rejectQuestion(question.sessionID, question.id);
@@ -296,7 +315,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
296315
} finally {
297316
setIsResponding(false);
298317
}
299-
}, [question.id, question.sessionID, rejectQuestion, t]);
318+
}, [orphaned, question.id, question.sessionID, question.tool?.callID, rejectQuestion, t]);
300319

301320
const handleCopyMarkdown = React.useCallback(async () => {
302321
const text = serializeQuestionAsMarkdown(question);
@@ -331,6 +350,11 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
331350
<div className="flex items-center gap-2">
332351
<Icon name="question" className="h-3.5 w-3.5 text-primary" />
333352
<span className="typography-meta font-medium text-muted-foreground">{t('chat.questionCard.inputNeeded')}</span>
353+
{orphaned ? (
354+
<span className="typography-micro px-1.5 py-0.5 rounded bg-[var(--status-warning-background)] text-[var(--status-warning)]">
355+
{t('chat.questionCard.orphanedBadge')}
356+
</span>
357+
) : null}
334358
{isFromSubagent ? (
335359
<span className="typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5">
336360
{t('chat.questionCard.fromSubagent')}
@@ -365,6 +389,11 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
365389
</div>
366390

367391
<div className="px-2 py-2">
392+
{orphaned ? (
393+
<div className="typography-micro text-muted-foreground mb-2">
394+
{t('chat.questionCard.orphanedNotice')}
395+
</div>
396+
) : null}
368397
{/* Minimal inline tabs for multiple questions */}
369398
{tabs.length > 1 ? (
370399
<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
@@ -1878,6 +1878,8 @@ export const dict = {
18781878
'chat.questionCard.submitFailed': 'Failed to send response',
18791879
'chat.questionCard.dismissFailed': 'Failed to dismiss question',
18801880
'chat.questionCard.noLongerPending': 'This question is no longer waiting for a response.',
1881+
'chat.questionCard.orphanedBadge': 'Interrupted',
1882+
'chat.questionCard.orphanedNotice': 'The session restarted before this question was answered. Your answer will be sent to the agent as a new message.',
18811883
'chat.questionCard.tryAgain': 'Please try again in a moment.',
18821884
'chat.textSelection.toast.noProject': 'No project found for this session',
18831885
'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
@@ -1856,6 +1856,8 @@ export const dict: Record<I18nKey, string> = {
18561856
"chat.questionCard.submitFailed": "No se pudo enviar la respuesta",
18571857
"chat.questionCard.dismissFailed": "No se pudo descartar la pregunta",
18581858
"chat.questionCard.noLongerPending": "Esta pregunta ya no espera una respuesta.",
1859+
"chat.questionCard.orphanedBadge": "Interrumpida",
1860+
"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.",
18591861
"chat.questionCard.tryAgain": "Inténtalo de nuevo en un momento.",
18601862
"chat.textSelection.toast.noProject": "No se encontró proyecto para esta sesión",
18611863
"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
@@ -2754,6 +2754,8 @@ export const dict = {
27542754
'chat.questionCard.submitFailed': 'Impossible d’envoyer la réponse',
27552755
'chat.questionCard.dismissFailed': 'Impossible d’ignorer la question',
27562756
'chat.questionCard.noLongerPending': 'Cette question n’attend plus de réponse.',
2757+
'chat.questionCard.orphanedBadge': 'Interrompue',
2758+
'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.',
27572759
'chat.questionCard.tryAgain': 'Veuillez réessayer dans un instant.',
27582760
'chat.messageBody.forkDialog.instructions.label': 'Instructions',
27592761
'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
@@ -1874,6 +1874,8 @@ export const dict: Record<I18nKey, string> = {
18741874
'chat.questionCard.submitFailed': '応答の送信に失敗しました',
18751875
'chat.questionCard.dismissFailed': '質問の閉じるのに失敗しました',
18761876
'chat.questionCard.noLongerPending': 'この質問は応答待ちではなくなりました。',
1877+
'chat.questionCard.orphanedBadge': '中断',
1878+
'chat.questionCard.orphanedNotice': 'この質問に回答する前にセッションが再起動されました。回答は新しいメッセージとしてエージェントに送信されます。',
18771879
'chat.questionCard.tryAgain': 'しばらくしてからもう一度お試しください。',
18781880
'chat.textSelection.toast.noProject': 'このセッションのプロジェクトが見つかりません',
18791881
'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
@@ -1880,6 +1880,8 @@ export const dict: Record<I18nKey, string> = {
18801880
'chat.questionCard.submitFailed': '응답 전송에 실패했습니다',
18811881
'chat.questionCard.dismissFailed': '질문 닫기에 실패했습니다',
18821882
'chat.questionCard.noLongerPending': '이 질문은 더 이상 응답을 기다리지 않습니다.',
1883+
'chat.questionCard.orphanedBadge': '중단됨',
1884+
'chat.questionCard.orphanedNotice': '이 질문에 답하기 전에 세션이 다시 시작되었습니다. 답변은 새 메시지로 에이전트에게 전송됩니다.',
18831885
'chat.questionCard.tryAgain': '잠시 후 다시 시도하세요.',
18841886
'chat.textSelection.toast.noProject': '이 세션의 프로젝트를 찾을 수 없음',
18851887
'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
@@ -759,6 +759,8 @@ export const dict: Record<I18nKey, string> = {
759759
'chat.questionCard.submitFailed': 'Nie udało się wysłać odpowiedzi',
760760
'chat.questionCard.dismissFailed': 'Nie udało się odrzucić pytania',
761761
'chat.questionCard.noLongerPending': 'To pytanie nie czeka już na odpowiedź.',
762+
'chat.questionCard.orphanedBadge': 'Przerwane',
763+
'chat.questionCard.orphanedNotice': 'Sesja została uruchomiona ponownie, zanim udzielono odpowiedzi na to pytanie. Twoja odpowiedź zostanie wysłana do agenta jako nowa wiadomość.',
762764
'chat.questionCard.tryAgain': 'Spróbuj ponownie za chwilę.',
763765
'chat.textSelection.toast.noProject': 'Nie znaleziono projektu dla tej sesji',
764766
'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
@@ -1856,6 +1856,8 @@ export const dict: Record<I18nKey, string> = {
18561856
"chat.questionCard.submitFailed": "Falha ao enviar a resposta",
18571857
"chat.questionCard.dismissFailed": "Falha ao descartar a pergunta",
18581858
"chat.questionCard.noLongerPending": "Esta pergunta não está mais aguardando uma resposta.",
1859+
"chat.questionCard.orphanedBadge": "Interrompida",
1860+
"chat.questionCard.orphanedNotice": "A sessão foi reiniciada antes desta pergunta ser respondida. Sua resposta será enviada ao agente como uma nova mensagem.",
18591861
"chat.questionCard.tryAgain": "Tente novamente em instantes.",
18601862
"chat.textSelection.toast.noProject": "Não foi encontrado projeto para esta sessão",
18611863
"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
@@ -1856,6 +1856,8 @@ export const dict: Record<I18nKey, string> = {
18561856
"chat.questionCard.submitFailed": "Не вдалося надіслати відповідь",
18571857
"chat.questionCard.dismissFailed": "Не вдалося відхилити питання",
18581858
"chat.questionCard.noLongerPending": "Це питання більше не очікує відповіді.",
1859+
"chat.questionCard.orphanedBadge": "Перервано",
1860+
"chat.questionCard.orphanedNotice": "Сесію було перезапущено до того, як на це питання відповіли. Вашу відповідь буде надіслано агенту як нове повідомлення.",
18591861
"chat.questionCard.tryAgain": "Спробуйте ще раз за мить.",
18601862
"chat.textSelection.toast.noProject": "Для цієї сесії не знайдено жодного проєкту",
18611863
"chat.textSelection.toast.addToNotesFailed": "Не вдалося додати до нотаток",

0 commit comments

Comments
 (0)