// The sidebar on the right: the assistant's conversation, and the review // of what is suggested and commented, each accepted or rejected on its own. // While the assistant is in use (a question composed, out, or just answered) // the sidebar is wide and says what the assistant is doing: the steps, the // tools an agent uses, the words as they come; once the writer is back in // the text it narrows again. The host's layout reads the `wide` class. import { LitElement, html, nothing } from 'lit'; import { SignalWatcher } from '@lit-labs/signals'; import type { Ask, Draft } from '../draft.ts'; import type { SuggestionItem } from '../suggestions/list.ts'; import { seconds, summariseActivity, type Activity } from '../activity.ts'; import { renderSwitch } from './switch.ts'; const WIDE_KEY = 'draft-sidebar-wide'; type Tab = 'assistant' | 'changes' | (string & {}); /** A tab a host adds to the sidebar (a library, an outline, whatever it has). */ export type SidebarPanel = { id: string; label: string; render: () => unknown; badge?: number | string; /** The tab's tooltip (the label and its shortcut, say). */ title?: string; /** The tab's icon (a Lucide name in supram's set); the label alone otherwise. */ icon?: string }; const KIND_LABEL: Record = { insertion: 'insert', deletion: 'delete', replacement: 'replace', formatting: 'format', 'block-insertion': 'new block', 'block-deletion': 'remove block', 'block-move': 'move block', 'block-split': 'split block', 'block-merge': 'merge blocks', 'block-expansion': 'written out', 'block-detail': 'broken down', 'outline-section': 'proposed section', 'outline-note': 'outline note', 'outline-points': 'the sentences', mixed: 'change', }; function when(iso: string): string { const d = new Date(iso); return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }); } export class DraftSidebar extends SignalWatcher(LitElement) { static properties = { draft: { attribute: false }, panels: { attribute: false }, core: { attribute: false }, tab: { state: true }, input: { state: true }, replyTo: { state: true }, replyText: { state: true }, showResolved: { state: true }, now: { state: true }, engaged: { state: true }, pinned: { state: true }, showThinking: { state: true } }; declare draft: Draft | null; declare panels: SidebarPanel[]; /** The sidebar's own tabs, the assistant's conversation and the changes; off, only the host's panels (a host that shows the assistant elsewhere). */ declare core: boolean; declare tab: Tab; declare input: string; declare replyTo: string | null; declare replyText: string; declare showResolved: boolean; /** Ticks once a second while a question is out, so the pane can say how long the wait has been. */ declare now: number; /** The writer's attention is on the assistant: composing, waiting, or reading the answer; the pane is wide meanwhile. */ declare engaged: boolean; /** The writer keeps the pane wide whatever happens. */ declare pinned: boolean; /** The model's reasoning is shown as it streams. */ declare showThinking: boolean; #ticker: ReturnType | null = null; constructor() { super(); this.draft = null; this.panels = []; this.core = true; this.tab = 'assistant'; this.input = ''; this.replyTo = null; this.replyText = ''; this.showResolved = false; this.now = 0; this.engaged = false; this.showThinking = false; let pinned = false; try { pinned = localStorage.getItem(WIDE_KEY) === '1'; } catch { // private mode: not kept } this.pinned = pinned; } protected override createRenderRoot() { return this; } override connectedCallback(): void { super.connectedCallback(); document.addEventListener('focusin', this.#focusin); } override disconnectedCallback(): void { super.disconnectedCallback(); document.removeEventListener('focusin', this.#focusin); if (this.#ticker) clearInterval(this.#ticker); this.#ticker = null; } /** The pane is engaged while the focus is in its conversation, and lets go once the writer is back in the text. */ #focusin = (e: FocusEvent): void => { const t = e.target; if (!(t instanceof Node)) return; if (this.contains(t)) { if (this.tab === 'assistant' && (t as Element).closest?.('.chat')) this.engaged = true; } else if (!this.draft?.busy.get()) this.engaged = false; }; /** Wide while the assistant is in use: a question composed, out, or just answered; or kept so by the writer. */ get wide(): boolean { return this.core && this.tab === 'assistant' && (this.pinned || this.engaged || !!this.draft?.busy.get()); } setPinned(on: boolean): void { this.pinned = on; try { localStorage.setItem(WIDE_KEY, on ? '1' : '0'); } catch { // private mode: this session only } } protected override willUpdate(): void { // a question out (asked here or by the host) engages the pane, and the answer is read at width if (this.core && this.draft?.busy.get() && !this.engaged) this.engaged = true; // without its own tabs the sidebar opens on the host's first panel if (!this.core && (this.tab === 'assistant' || this.tab === 'changes') && this.panels[0]) this.tab = this.panels[0].id; } override updated(): void { this.classList.toggle('wide', this.wide); // keep the conversation, and the words streaming in, scrolled to their end const log = this.querySelector('.chat-log'); if (log && this.tab === 'assistant') log.scrollTop = log.scrollHeight; for (const pre of this.querySelectorAll('.thinking .stream')) pre.scrollTop = pre.scrollHeight; // tick while a question is out const busy = !!this.draft?.busy.get(); if (busy && !this.#ticker) this.#ticker = setInterval(() => (this.now = Date.now()), 1000); else if (!busy && this.#ticker) { clearInterval(this.#ticker); this.#ticker = null; } } /** How long the question now out has been waiting, once that is worth saying: "12 s", "1 min 30 s". */ #waited(): string | null { const since = this.draft?.askedAt.get() ?? 0; if (!since) return null; const s = Math.floor((Math.max(this.now, since) - since) / 1000); if (s < 5) return null; return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`; } async #ask(text = this.input): Promise { const d = this.draft; if (!d || !text.trim()) return; this.input = ''; this.engaged = true; await d.ask(text); } async #copyDocument(): Promise { const d = this.draft; if (!d) return; const { ASSISTANT_INSTRUCTIONS } = await import('../suggestions/protocol.ts'); const style = d.styleText(); const context = d.contextText(); const text = `${ASSISTANT_INSTRUCTIONS}${style ? `\n\n${style}` : ''}\n\n---\n\n${context ? `${context}\n\n---\n\n` : ''}${d.documentText()}`; try { await navigator.clipboard.writeText(text); this.dispatchEvent(new CustomEvent('notice', { detail: 'Copied the document and the instructions for a model.', bubbles: true })); } catch { this.dispatchEvent(new CustomEvent('notice', { detail: 'Could not copy; select the text in the editor instead.', bubbles: true })); } } #renderAssistant() { const d = this.draft!; const a = d.assistant.get(); const asks = d.asks.get().filter((a) => a.status !== 'queued'); const busy = d.busy.get(); if (!a) { return html`

No assistant is configured for this document.

`; } return html`
${asks.length === 0 ? html`

Ask for changes. I answer with suggestions you can accept or reject one at a time, and with comments where I would rather ask than change.

${a.name}

` : nothing} ${asks.map((a) => this.#renderAsk(a))} ${busy ? this.#renderWorking(a.name, d.activity.get()) : nothing}
${a.prompts?.length ? html`
${a.prompts.map((p) => html``)}
` : nothing}
{ e.preventDefault(); this.#ask(); }} >
${asks.length ? html`` : nothing}
`; } /** While a question is out: who is at it and for how long, the steps so far, the words as they come, and a way to stop. */ #renderWorking(name: string, act: Activity | null) { const d = this.draft!; const waited = this.#waited(); return html`
${name} ${waited ? html`${waited}` : nothing}
${act ? this.#renderSteps(act, true) : nothing} ${act?.thinking ? html`
(this.showThinking = (e.target as HTMLDetailsElement).open)}> Thinking (${act.thinking.length.toLocaleString()} characters)
${act.thinking.slice(-4000)}
` : nothing} ${act?.text ? html`
The reply so far: ${act.text.length.toLocaleString()} characters${act.firstWords !== undefined ? `, the first after ${seconds(act.firstWords)}` : ''}
${act.text.slice(-4000)}
` : nothing}
`; } /** The steps of an activity, with when each happened; the last one is the current one while the work goes on. */ #renderSteps(act: Activity, live: boolean) { const steps = act.steps; if (!steps.length) return nothing; return html`
    ${steps.map( (s, i) => html`
  1. ${seconds(s.at)} ${s.kind === 'tool' ? html`${s.text} ${s.input}${s.result !== undefined ? html`${s.result}` : nothing}` : html`${s.text}`}
  2. `, )}
`; } /** What an answered question's assistant did, folded under the reply. */ #renderActivity(act: Activity) { const thought = act.thinking ? `, ${act.thinking.length.toLocaleString()} characters of thinking` : ''; return html`
${summariseActivity(act)}${thought} ${this.#renderSteps(act, false)} ${act.thinking ? html`
Thinking
${act.thinking}
` : nothing} ${act.text ? html`
The reply as it came (${act.text.length.toLocaleString()} characters)
${act.text}
` : nothing}
`; } /** An ask as two turns: what was asked, and what came back with what it proposed. */ #renderAsk(a: Ask) { const d = this.draft!; const live = new Set(d.suggestions.get().map((s) => s.id)); const pending = a.suggestions.filter((id) => live.has(id)); const comments = a.suggestions.filter((id) => d.comments.get().some((c) => c.id === id && !c.resolved)).length; const working = a.status === 'working'; return html`
${a.instruction}
${when(a.at)}
${working ? nothing : html`
${a.reply ?? ''}
${a.suggestions.length || a.failed?.length ? html`
${pending.length ? html`${pending.length} pending suggestion${pending.length === 1 ? '' : 's'} ` : a.suggestions.length ? html`${comments ? `${comments} comment${comments === 1 ? '' : 's'}` : 'all reviewed'}` : nothing} ${a.failed?.length ? html`
${a.failed.length} could not be applied
    ${a.failed.map((f) => html`
  • ${f.op.op} — ${f.reason}
  • `)}
` : nothing}
` : nothing} ${a.activity ? this.#renderActivity(a.activity) : nothing}
${when(a.activity?.ended ? new Date(a.activity.ended).toISOString() : a.at)}
`}`; } #renderChanges() { const d = this.draft!; const items = d.suggestions.get(); const comments = d.comments.get(); const open = comments.filter((c) => !c.resolved); const resolved = comments.filter((c) => c.resolved); const suggesting = d.suggesting.get(); return html`
${renderSwitch('Suggesting', suggesting, () => d.setSuggesting(!suggesting), { title: `Suggesting ${suggesting ? 'on' : 'off'} — while on, your own edits are suggestions, tracked until accepted` })}
Suggestions ${items.length ? html` ` : nothing}
${items.length === 0 ? html`

No pending suggestions. Turn on Suggesting and edit, or ask the assistant.

` : nothing}
    ${items.map((s) => this.#renderSuggestion(s))}
Comments ${resolved.length ? html`` : nothing}
${open.length === 0 ? html`

No open comments. Select text and press ⌘⇧M, or use the block menu (⋮⋮).

` : nothing}
    ${open.map((c) => this.#renderComment(c))} ${this.showResolved ? resolved.map((c) => this.#renderComment(c)) : nothing}
`; } #renderSuggestion(s: SuggestionItem) { const d = this.draft!; const who = s.meta?.author; return html`
  • d.show(s.id)}>
    ${KIND_LABEL[s.kind]} ${who ? html`${who.name}` : nothing}
    ${s.deleted ? html`${s.deleted}` : nothing} ${s.inserted ? html`${s.inserted}` : nothing} ${s.changes.length ? html`${s.changes.join(', ')}` : nothing}
    ${s.meta?.note ? html`
    ${s.meta.note}
    ` : nothing}
  • `; } #renderComment(c: import('../draft.ts').CommentView) { const d = this.draft!; const replying = this.replyTo === c.id; return html`
  • c.from !== undefined && c.to !== undefined && d.showRange(c.from, c.to)}>
    ${c.author.name} ${when(c.at)} ${c.resolved ? html`` : html``}
    ${c.quote ? html`
    “${c.quote}”
    ` : nothing}
    ${c.text}
    ${c.replies.map((r) => html`
    ${r.author.name} ${r.text}
    `)} ${c.resolved ? nothing : replying ? html`
    e.stopPropagation()} @submit=${(e: Event) => { e.preventDefault(); d.reply(c.id, this.replyText); this.replyText = ''; this.replyTo = null; }} > (this.replyText = (e.target as HTMLInputElement).value)} @keydown=${(e: KeyboardEvent) => e.stopPropagation()} />
    ` : html``}
  • `; } /** A tab: its icon and its name (the name alone in a sidebar too narrow for both, where the tooltip says it). */ #renderTab(id: string, label: string, icon: string | undefined, title: string, badge?: number | string) { const on = this.tab === id; return html``; } override render() { const d = this.draft; if (!d) return nothing; const pending = d.suggestions.get().length + d.comments.get().filter((c) => !c.resolved).length; return html`
    ${this.core ? this.#renderTab('assistant', 'Assistant', 'sparkles', 'The assistant: ask for changes, get suggestions') : nothing} ${this.core ? this.#renderTab('changes', 'Changes', 'list-checks', 'Pending suggestions and comments', pending || undefined) : nothing} ${this.panels.map((p) => this.#renderTab(p.id, p.label, p.icon, p.title ?? p.label, p.badge))}
    ${this.tab === 'assistant' ? this.#renderAssistant() : this.tab === 'changes' ? this.#renderChanges() : (this.panels.find((p) => p.id === this.tab)?.render() ?? nothing)}
    `; } } customElements.define('draft-sidebar', DraftSidebar);