Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 128 additions & 0 deletions src/components/Draft/DraftResponsePanel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// @vitest-environment jsdom
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { DraftResponsePanel } from "./DraftResponsePanel";

vi.mock("./ResponsePanel", () => ({
ResponsePanel: ({ response }: { response: string }) => (
<div data-testid="response-panel">{response || "empty"}</div>
),
}));

vi.mock("./AlternativePanel", () => ({
AlternativePanel: () => <div data-testid="alternative-panel" />,
}));

vi.mock("./SavedResponsesSuggestion", () => ({
SavedResponsesSuggestion: () => <div data-testid="saved-suggestion" />,
}));

function makeProps(
overrides: Partial<Parameters<typeof DraftResponsePanel>[0]> = {},
) {
return {
suggestions: [],
suggestionsDismissed: false,
onSuggestionApply: vi.fn(),
onSuggestionDismiss: vi.fn(),
response: "",
streamingText: "",
isStreaming: false,
sources: [],
generating: false,
metrics: null,
confidence: null,
grounding: [],
savedDraftId: null,
hasInput: false,
isResponseEdited: false,
loadedModelName: null,
currentTicketId: null,
onSaveDraft: vi.fn(),
onCancel: vi.fn(),
onResponseChange: vi.fn(),
onGenerateAlternative: vi.fn(),
generatingAlternative: false,
onSaveAsTemplate: vi.fn(),
alternatives: [],
onChooseAlternative: vi.fn(),
onUseAlternative: vi.fn(),
...overrides,
};
}

describe("DraftResponsePanel", () => {
afterEach(() => cleanup());

it("renders the response panel by itself when no suggestions or alternatives are present", () => {
render(<DraftResponsePanel {...makeProps()} />);

expect(screen.getByTestId("response-panel")).toBeTruthy();
expect(screen.queryByTestId("saved-suggestion")).toBeNull();
expect(screen.queryByTestId("alternative-panel")).toBeNull();
});

it("shows the saved-responses suggestion when suggestions exist, no response, and not dismissed", () => {
render(
<DraftResponsePanel
{...makeProps({
suggestions: [
{
id: "t1",
name: "t",
content: "snippet",
created_at: "",
updated_at: "",
usage_count: 0,
} as unknown as Parameters<
typeof DraftResponsePanel
>[0]["suggestions"][number],
],
})}
/>,
);

expect(screen.getByTestId("saved-suggestion")).toBeTruthy();
});

it("hides the suggestion once the user has a response", () => {
render(
<DraftResponsePanel {...makeProps({ response: "generated text" })} />,
);

expect(screen.queryByTestId("saved-suggestion")).toBeNull();
expect(screen.getByTestId("response-panel").textContent).toBe(
"generated text",
);
});

it("shows the alternative panel only when alternatives exist and generation is idle", () => {
const baseAlt = {
id: "a",
original_text: "o",
alternative_text: "new",
created_at: "",
chosen: null,
} as unknown as Parameters<
typeof DraftResponsePanel
>[0]["alternatives"][number];

const { rerender } = render(
<DraftResponsePanel
{...makeProps({ response: "x", alternatives: [baseAlt] })}
/>,
);
expect(screen.getByTestId("alternative-panel")).toBeTruthy();

rerender(
<DraftResponsePanel
{...makeProps({
response: "x",
alternatives: [baseAlt],
generating: true,
})}
/>,
);
expect(screen.queryByTestId("alternative-panel")).toBeNull();
});
});
121 changes: 121 additions & 0 deletions src/components/Draft/DraftResponsePanel.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { AlternativePanel } from "./AlternativePanel";
import { ResponsePanel } from "./ResponsePanel";
import { SavedResponsesSuggestion } from "./SavedResponsesSuggestion";
import type { ContextSource } from "../../types/knowledge";
import type {
ConfidenceAssessment,
GenerationMetrics,
GroundedClaim,
} from "../../types/llm";
import type {
ResponseAlternative,
SavedResponseTemplate,
} from "../../types/workspace";

interface DraftResponsePanelProps {
suggestions: SavedResponseTemplate[];
suggestionsDismissed: boolean;
onSuggestionApply: (content: string, templateId: string) => void;
onSuggestionDismiss: () => void;

response: string;
streamingText: string;
isStreaming: boolean;
sources: ContextSource[];
generating: boolean;
metrics: GenerationMetrics | null;
confidence: ConfidenceAssessment | null;
grounding: GroundedClaim[];
savedDraftId: string | null;
hasInput: boolean;
isResponseEdited: boolean;
loadedModelName: string | null;
currentTicketId: string | null;
onSaveDraft: () => void;
onCancel: () => void;
onResponseChange: (text: string) => void;
onGenerateAlternative: () => void;
generatingAlternative: boolean;
onSaveAsTemplate: (rating: number) => void;

alternatives: ResponseAlternative[];
onChooseAlternative: (
alternativeId: string,
choice: "original" | "alternative",
) => void;
onUseAlternative: (text: string) => void;
}

export function DraftResponsePanel({
suggestions,
suggestionsDismissed,
onSuggestionApply,
onSuggestionDismiss,
response,
streamingText,
isStreaming,
sources,
generating,
metrics,
confidence,
grounding,
savedDraftId,
hasInput,
isResponseEdited,
loadedModelName,
currentTicketId,
onSaveDraft,
onCancel,
onResponseChange,
onGenerateAlternative,
generatingAlternative,
onSaveAsTemplate,
alternatives,
onChooseAlternative,
onUseAlternative,
}: DraftResponsePanelProps) {
const showSuggestions =
!suggestionsDismissed && suggestions.length > 0 && !response;
const showAlternatives =
alternatives.length > 0 && response && !generating && !isStreaming;

return (
<>
{showSuggestions ? (
<SavedResponsesSuggestion
suggestions={suggestions}
onApply={onSuggestionApply}
onDismiss={onSuggestionDismiss}
/>
) : null}
<ResponsePanel
response={response}
streamingText={streamingText}
isStreaming={isStreaming}
sources={sources}
generating={generating}
metrics={metrics}
confidence={confidence}
grounding={grounding}
draftId={savedDraftId}
onSaveDraft={onSaveDraft}
onCancel={onCancel}
hasInput={hasInput}
onResponseChange={onResponseChange}
isEdited={isResponseEdited}
modelName={loadedModelName}
onGenerateAlternative={onGenerateAlternative}
generatingAlternative={generatingAlternative}
ticketKey={currentTicketId}
onSaveAsTemplate={onSaveAsTemplate}
/>
{showAlternatives ? (
<AlternativePanel
alternatives={alternatives}
onChoose={onChooseAlternative}
onUseAlternative={onUseAlternative}
/>
) : null}
</>
);
}
46 changes: 46 additions & 0 deletions src/components/Draft/DraftTab.handle.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import type { DraftTabHandle } from "./DraftTab";

// Compile-time pin: a drift-detector that fails to typecheck if DraftTabHandle
// gains, loses, or renames a member. 8 consumers import this handle type; any
// surface change must be intentional and reviewed here.

type ExpectedHandle = {
generate: () => void;
loadDraft: (draft: unknown) => void;
saveDraft: () => void;
copyResponse: () => void;
cancelGeneration: () => void;
exportResponse: () => void;
clearDraft: () => void;
};

type HandleMatchesShape = DraftTabHandle extends ExpectedHandle
? ExpectedHandle extends { [K in keyof DraftTabHandle]: DraftTabHandle[K] }
? true
: false
: false;

const _handleShapeCheck: HandleMatchesShape = true;
void _handleShapeCheck;

describe("DraftTabHandle shape", () => {
it("exposes the seven imperative methods consumers rely on", () => {
const expectedKeys = [
"generate",
"loadDraft",
"saveDraft",
"copyResponse",
"cancelGeneration",
"exportResponse",
"clearDraft",
] as const;

// Runtime no-op; pairs with the compile-time pin above. The assertion
// exists so test runners list the check alongside the type guard.
for (const key of expectedKeys) {
expect(key).toBeDefined();
}
});
});
69 changes: 29 additions & 40 deletions src/components/Draft/DraftTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@
useMemo,
} from "react";
import { invoke } from "@tauri-apps/api/core";
import { DraftResponsePanel } from "./DraftResponsePanel";
import { InputPanel } from "./InputPanel";
import { DiagnosisPanel, TreeResult } from "./DiagnosisPanel";
import { ResponsePanel } from "./ResponsePanel";
import { AlternativePanel } from "./AlternativePanel";
import { SavedResponsesSuggestion } from "./SavedResponsesSuggestion";
import { ConversationThread, ConversationEntry } from "./ConversationThread";
import { useDraftApproval } from "./useDraftApproval";
import { useDraftChecklist } from "./useDraftChecklist";
Expand Down Expand Up @@ -517,7 +515,7 @@
return next;
});
},
[savedDraftId],

Check warning on line 518 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setCaseIntake'. Either include it or remove the dependency array
);

const handleRefreshSimilarCases = useCallback(async () => {
Expand Down Expand Up @@ -690,7 +688,7 @@
setPendingSimilarCaseOpen(null);
setWorkspaceRunbookScopeKey(createWorkspaceRunbookScopeKey());
resetGeneration();
}, [workspacePersonalization.preferred_note_audience, resetGeneration]);

Check warning on line 691 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has missing dependencies: 'resetApproval', 'resetChecklist', 'resetFirstResponse', 'setCaseIntake', 'setGuidedRunbookSession', 'setPendingSimilarCaseOpen', 'setRunbookSessionSourceScopeKey', and 'setRunbookSessionTouched'. Either include them or remove the dependency array

const handleResponseChange = useCallback(
(text: string) => {
Expand Down Expand Up @@ -775,7 +773,7 @@
setGenerating(false);
}
},
[modelLoaded, responseLength, generateStreaming, clearStreamingText],

Check warning on line 776 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setGenerating'. Either include it or remove the dependency array
);

const handleCancel = useCallback(async () => {
Expand All @@ -787,7 +785,7 @@
setOriginalResponse(streamingText);
setIsResponseEdited(false);
}
}, [cancelGeneration, streamingText]);

Check warning on line 788 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setGenerating'. Either include it or remove the dependency array

useEffect(() => {
if (viewMode !== "panels") {
Expand Down Expand Up @@ -1200,7 +1198,7 @@
});
showSuccess(`Applied ${kit.name}`);
},
[input, response, caseIntake, logEvent, currentTicketId, showSuccess],

Check warning on line 1201 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setCaseIntake'. Either include it or remove the dependency array
);

const handleToggleWorkspaceFavorite = useCallback(
Expand Down Expand Up @@ -1289,7 +1287,7 @@
showError("Failed to start guided runbook");
}
},
[

Check warning on line 1290 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has missing dependencies: 'setRunbookSessionSourceScopeKey' and 'setRunbookSessionTouched'. Either include them or remove the dependency array
runbookTemplates,
startRunbookSession,
refreshWorkspaceCatalog,
Expand Down Expand Up @@ -1370,7 +1368,7 @@
showError("Failed to update guided runbook progress");
}
},
[

Check warning on line 1371 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setRunbookSessionTouched'. Either include it or remove the dependency array
guidedRunbookSession,
guidedRunbookNote,
addRunbookStepEvidence,
Expand Down Expand Up @@ -1408,7 +1406,7 @@
if (value.trim()) {
setRunbookSessionTouched(true);
}
}, []);

Check warning on line 1409 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setRunbookSessionTouched'. Either include it or remove the dependency array

const loadSimilarCaseIntoWorkspace = useCallback(
async (similarCase: SimilarCase) => {
Expand Down Expand Up @@ -1440,7 +1438,7 @@
showError("Failed to open similar case");
}
},
[

Check warning on line 1441 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has a missing dependency: 'setPendingSimilarCaseOpen'. Either include it or remove the dependency array
loadSimilarCaseIntoWorkspace,
logEvent,
currentTicketId,
Expand Down Expand Up @@ -1534,7 +1532,7 @@

void handleCopyKbDraft();
},
[

Check warning on line 1535 in src/components/Draft/DraftTab.tsx

View workflow job for this annotation

GitHub Actions / quality-gates

React Hook useCallback has missing dependencies: 'setApprovalQuery' and 'setCaseIntake'. Either include them or remove the dependency array
logEvent,
currentTicketId,
handleGenerate,
Expand Down Expand Up @@ -1994,43 +1992,34 @@
);

const responsePanel = (
<>
{!suggestionsDismissed && suggestions.length > 0 && !response ? (
<SavedResponsesSuggestion
suggestions={suggestions}
onApply={handleSuggestionApply}
onDismiss={handleSuggestionDismiss}
/>
) : null}
<ResponsePanel
response={response}
streamingText={streamingText}
isStreaming={isStreaming}
sources={sources}
generating={generating}
metrics={metrics}
confidence={confidence}
grounding={grounding}
draftId={savedDraftId}
onSaveDraft={handleSaveDraft}
onCancel={handleCancel}
hasInput={!!input.trim()}
onResponseChange={handleResponseChange}
isEdited={isResponseEdited}
modelName={loadedModelName}
onGenerateAlternative={handleGenerateAlternative}
generatingAlternative={generatingAlternative}
ticketKey={currentTicketId}
onSaveAsTemplate={handleSaveAsTemplate}
/>
{alternatives.length > 0 && response && !generating && !isStreaming ? (
<AlternativePanel
alternatives={alternatives}
onChoose={handleChooseAlternative}
onUseAlternative={handleUseAlternative}
/>
) : null}
</>
<DraftResponsePanel
suggestions={suggestions}
suggestionsDismissed={suggestionsDismissed}
onSuggestionApply={handleSuggestionApply}
onSuggestionDismiss={handleSuggestionDismiss}
response={response}
streamingText={streamingText}
isStreaming={isStreaming}
sources={sources}
generating={generating}
metrics={metrics}
confidence={confidence}
grounding={grounding}
savedDraftId={savedDraftId}
hasInput={!!input.trim()}
isResponseEdited={isResponseEdited}
loadedModelName={loadedModelName}
currentTicketId={currentTicketId}
onSaveDraft={handleSaveDraft}
onCancel={handleCancel}
onResponseChange={handleResponseChange}
onGenerateAlternative={handleGenerateAlternative}
generatingAlternative={generatingAlternative}
onSaveAsTemplate={handleSaveAsTemplate}
alternatives={alternatives}
onChooseAlternative={handleChooseAlternative}
onUseAlternative={handleUseAlternative}
/>
);

const workspacePanel = (
Expand Down
Loading