-
Notifications
You must be signed in to change notification settings - Fork 286
Generate system instructions from chat history #403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gyanu2507
wants to merge
8
commits into
truefoundry:main
Choose a base branch
from
gyanu2507:feat/generate-instructions-from-chat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
102de33
Generate system instructions from an existing chat history.
gyanu2507 7bd3112
Infer generated-instruction types from the Zod schemas.
gyanu2507 939f8e5
Drop unused re-exports of the generated-instruction types.
gyanu2507 d005af0
Ignore overlapping From chat generate requests.
gyanu2507 0672b2f
Ignore overlapping From chat apply requests.
gyanu2507 422ae29
Count only user text toward the generate-from-chat length gate.
74e33f4
Map missing session turns on generate-instructions to 404.
243929c
Declare 400 on generate-instructions for store conflicts.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| "@truefoundry/trueforge": patch | ||
| "@truefoundry/trueforge-ui": patch | ||
| --- | ||
|
|
||
| Draft system instructions from an existing chat, then let the user edit before applying |
254 changes: 254 additions & 0 deletions
254
packages/trueforge-ui/src/atoms/GenerateInstructionsButton.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,254 @@ | ||
| 'use client'; | ||
|
|
||
| import { | ||
| useTrueFoundryAdoptAgentSpec, | ||
| useTrueFoundryAgentSpec, | ||
| useTrueFoundryFlushAgentSpec, | ||
| } from '@truefoundry/assistant-ui-runtime'; | ||
| import { useEffect, useId, useRef, useState } from 'react'; | ||
| import { useAuiState } from '../assistant-ui.js'; | ||
| import { Icon } from '../icons/Icon.js'; | ||
| import { hasGenerateInstructionsFromChat } from '../server/generateInstructionsFromChat.js'; | ||
| import { useOptionalServer } from '../server/ServerContext.js'; | ||
| import { useOptionalShellMode } from '../server/ShellModeContext.js'; | ||
| import { getErrorMessage } from '../utils/getErrorMessage.js'; | ||
| import { auiButtonClass } from './lib/buttonClasses.js'; | ||
| import { auiInputClass } from './lib/inputClasses.js'; | ||
| import { CenteredModal } from './primitives/CenteredModal.js'; | ||
|
|
||
| export type GenerateInstructionsButtonProps = { | ||
| disabled?: boolean; | ||
| className?: string; | ||
| }; | ||
|
|
||
| export function useGenerateInstructionsVisible(): boolean { | ||
| const shell = useOptionalShellMode(); | ||
| const server = useOptionalServer(); | ||
| const remoteId = useAuiState(s => s.threadListItem.remoteId); | ||
| if (shell == null || shell.mode.status !== 'active') return false; | ||
| if (remoteId == null || remoteId.length === 0) return false; | ||
| return hasGenerateInstructionsFromChat(server); | ||
| } | ||
|
|
||
| export function GenerateInstructionsButton({ disabled = false, className }: GenerateInstructionsButtonProps) { | ||
| const visible = useGenerateInstructionsVisible(); | ||
| if (!visible) return null; | ||
| return <GenerateInstructionsButtonContent disabled={disabled} className={className} />; | ||
| } | ||
|
|
||
| function GenerateInstructionsButtonContent({ disabled, className }: { disabled: boolean; className?: string }) { | ||
| const server = useOptionalServer(); | ||
| const shell = useOptionalShellMode(); | ||
| const remoteId = useAuiState(s => s.threadListItem.remoteId); | ||
| const { agentSpec } = useTrueFoundryAgentSpec(); | ||
| const agentSpecRef = useRef(agentSpec); | ||
| agentSpecRef.current = agentSpec; | ||
| const flushAgentSpec = useTrueFoundryFlushAgentSpec(); | ||
| const adoptAgentSpec = useTrueFoundryAdoptAgentSpec(); | ||
| const titleId = useId(); | ||
| const [open, setOpen] = useState(false); | ||
| const [loading, setLoading] = useState(false); | ||
| const [applying, setApplying] = useState(false); | ||
| const [draft, setDraft] = useState(''); | ||
| const [sources, setSources] = useState<Array<{ turnId: string; role: 'user' | 'assistant'; excerpt: string }>>([]); | ||
| const [error, setError] = useState<string | null>(null); | ||
| const [copied, setCopied] = useState(false); | ||
| const errorRef = useRef<HTMLParagraphElement>(null); | ||
| const inFlightRef = useRef(false); | ||
| const applyingRef = useRef(false); | ||
| const canApply = shell?.mode.status === 'active' && shell.mode.isMutable && agentSpec != null; | ||
|
|
||
| useEffect(() => { | ||
| if (error === null) return; | ||
| errorRef.current?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' }); | ||
| }, [error]); | ||
|
|
||
| const close = () => { | ||
| if (loading || applying) return; | ||
| setOpen(false); | ||
| setDraft(''); | ||
| setSources([]); | ||
| setError(null); | ||
| setCopied(false); | ||
| }; | ||
|
|
||
| const generate = async () => { | ||
| if (!hasGenerateInstructionsFromChat(server) || remoteId == null || inFlightRef.current) return; | ||
| inFlightRef.current = true; | ||
| setLoading(true); | ||
| setError(null); | ||
| setCopied(false); | ||
| try { | ||
| const result = await server.generateInstructionsFromChat({ sessionId: remoteId }); | ||
| setDraft(result.instructions); | ||
| setSources(result.sources); | ||
| } catch (caught) { | ||
| setDraft(''); | ||
| setSources([]); | ||
| setError(getErrorMessage(caught, 'Could not generate instructions from this chat')); | ||
| } finally { | ||
| inFlightRef.current = false; | ||
| setLoading(false); | ||
| } | ||
| }; | ||
|
|
||
| const show = () => { | ||
| if (inFlightRef.current || applyingRef.current || loading || applying) return; | ||
| setOpen(true); | ||
| void generate(); | ||
| }; | ||
|
|
||
| const apply = async () => { | ||
| if ( | ||
| !canApply || | ||
| agentSpecRef.current === null || | ||
| remoteId == null || | ||
| !hasGenerateInstructionsFromChat(server) || | ||
| applyingRef.current | ||
| ) { | ||
| return; | ||
| } | ||
| const instructions = draft.trim(); | ||
| if (instructions.length === 0) return; | ||
| applyingRef.current = true; | ||
| setApplying(true); | ||
| setError(null); | ||
| try { | ||
| await flushAgentSpec(); | ||
| const latest = agentSpecRef.current; | ||
| if (latest === null) return; | ||
| const next = { ...latest, instructions }; | ||
| const updated = await server.updateSession({ sessionId: remoteId, agentSpec: next }); | ||
| adoptAgentSpec({ agentSpec: next, updatedAt: updated.updatedAt }); | ||
| setOpen(false); | ||
| setDraft(''); | ||
| setSources([]); | ||
| } catch (caught) { | ||
| setError(getErrorMessage(caught, 'Could not apply instructions to this chat')); | ||
| } finally { | ||
| applyingRef.current = false; | ||
| setApplying(false); | ||
| } | ||
| }; | ||
|
cursor[bot] marked this conversation as resolved.
|
||
|
|
||
| const copyDraft = async () => { | ||
| if (draft.trim().length === 0 || typeof navigator === 'undefined' || navigator.clipboard == null) return; | ||
| await navigator.clipboard.writeText(draft); | ||
| setCopied(true); | ||
| }; | ||
|
|
||
| return ( | ||
| <> | ||
| <button | ||
| type="button" | ||
| disabled={disabled || loading || applying || open} | ||
| className={auiButtonClass({ variant: 'ghost', size: 'sm', className })} | ||
| onClick={show} | ||
| > | ||
| <Icon name="lightbulb" className="size-3.5" /> | ||
| From chat | ||
| </button> | ||
|
|
||
| <CenteredModal | ||
| open={open} | ||
| onOpenChange={next => !next && close()} | ||
| title="Instructions from this chat" | ||
| className="md:h-auto md:max-h-[85dvh] md:max-w-2xl" | ||
| aria-label="Instructions from this chat" | ||
| > | ||
| <div className="flex min-h-0 w-full flex-1 flex-col"> | ||
| <div className="min-h-0 flex-1 overflow-y-auto px-5 py-3"> | ||
| <p className="text-text-secondary mb-3 text-sm"> | ||
| This is a draft from the conversation. Edit it before it becomes this chat's system instructions. | ||
| Nothing is saved until you apply it. | ||
| </p> | ||
|
|
||
| <label className="mb-3 block" htmlFor={titleId}> | ||
| <span className="mb-1.5 block text-sm font-medium">Suggested instructions</span> | ||
| <textarea | ||
| id={titleId} | ||
| value={draft} | ||
| disabled={loading || applying} | ||
| onChange={event => setDraft(event.target.value)} | ||
| rows={8} | ||
| placeholder={loading ? 'Reading this chat…' : 'No suggestion yet.'} | ||
| className={auiInputClass('resize-y py-2 disabled:opacity-60')} | ||
| /> | ||
| </label> | ||
|
|
||
| {sources.length > 0 ? ( | ||
| <div className="mb-3"> | ||
| <p className="text-text-secondary mb-1.5 text-xs font-semibold tracking-wide uppercase"> | ||
| Inferred from | ||
| </p> | ||
| <ul className="space-y-1.5"> | ||
| {sources.map(source => ( | ||
| <li | ||
| key={`${source.turnId}-${source.role}-${source.excerpt}`} | ||
| className="text-text-secondary text-xs" | ||
| > | ||
| <span className="text-text-primary font-medium">{source.role}</span> | ||
| {': '} | ||
| {source.excerpt} | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| </div> | ||
| ) : null} | ||
|
|
||
| {canApply ? null : ( | ||
| <p className="text-text-secondary mb-2 text-xs"> | ||
| This chat is bound to a saved agent, so the draft is not applied here. Copy it, or save a new agent. | ||
| </p> | ||
| )} | ||
|
|
||
| {error ? ( | ||
| <p | ||
| ref={errorRef} | ||
| role="alert" | ||
| className="text-failure-bg mt-2 text-sm wrap-break-word whitespace-pre-wrap" | ||
| > | ||
| {error} | ||
| </p> | ||
| ) : null} | ||
| </div> | ||
|
|
||
| <div className="bg-card-bg sticky bottom-0 z-10 flex shrink-0 flex-wrap justify-end gap-2 border-t border-border px-5 py-4"> | ||
| <button | ||
| type="button" | ||
| disabled={loading || applying} | ||
| className={auiButtonClass({ variant: 'secondary' })} | ||
| onClick={close} | ||
| > | ||
| Cancel | ||
| </button> | ||
| <button | ||
| type="button" | ||
| disabled={loading || applying || draft.trim().length === 0} | ||
| className={auiButtonClass({ variant: 'secondary' })} | ||
| onClick={() => void copyDraft()} | ||
| > | ||
| {copied ? 'Copied' : 'Copy'} | ||
| </button> | ||
| {canApply ? ( | ||
| <button | ||
| type="button" | ||
| disabled={loading || applying || draft.trim().length === 0} | ||
| className={auiButtonClass({ variant: 'default' })} | ||
| onClick={() => void apply()} | ||
| > | ||
| {applying ? 'Applying…' : 'Apply to this chat'} | ||
| </button> | ||
| ) : null} | ||
| </div> | ||
| </div> | ||
| </CenteredModal> | ||
| </> | ||
| ); | ||
| } | ||
|
|
||
| declare module '../theme/SlotsProvider.js' { | ||
| interface AtomSlots { | ||
| GenerateInstructionsButton: typeof GenerateInstructionsButton; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.