File size: 12,878 Bytes
98c8696
c72f0a1
98c8696
 
a9ff272
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
98c8696
 
 
 
 
 
 
a9ff272
98c8696
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
98c8696
 
 
 
 
 
 
 
 
c72f0a1
 
 
a9ff272
 
98c8696
 
 
 
c72f0a1
98c8696
 
 
 
 
 
 
 
c72f0a1
98c8696
c72f0a1
98c8696
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ff272
c72f0a1
a9ff272
 
c72f0a1
a9ff272
 
 
 
 
98c8696
 
 
 
c72f0a1
98c8696
 
c72f0a1
 
98c8696
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
c72f0a1
 
98c8696
c72f0a1
98c8696
 
 
 
 
 
a9ff272
98c8696
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import { Fragment, createElement, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import type { FormEvent, ReactNode } from "react";
// @ts-expect-error TS7016: Frozen marked 4.3.0 has no declarations; its consumed API is typed below.
import { marked as untypedMarked } from "marked";
import { fileDate, IntelligenceApiError, intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceProposal } from "./intelligenceApi";
import PromptView from "./PromptView";
import Proposals from "./Proposals";
import History from "./History";

interface MarkdownToken {
  type: string; text?: string; raw?: string; tokens?: MarkdownToken[]; depth?: number;
  href?: string; ordered?: boolean; start?: number; items?: MarkdownToken[];
  header?: MarkdownToken[]; rows?: MarkdownToken[][]; task?: boolean; checked?: boolean;
}
const markdownParser: { lexer(source: string): MarkdownToken[] } = untypedMarked;

function safeLink(href = ""): string | undefined {
  if (/^#\//.test(href)) return href;
  try {
    const url = new URL(href);
    if (["https:", "http:", "mailto:"].includes(url.protocol) && !url.username && !url.password) return href;
  } catch { /* A relative file path has no navigation contract. */ }
  return undefined;
}
/** Use the installed Markdown parser, with React nodes instead of an HTML injection sink. */
function markdownNodes(tokens: MarkdownToken[]): ReactNode {
  return tokens.map((token, index) => {
    const children = token.tokens ? markdownNodes(token.tokens) : token.text || "";
    let node: ReactNode;
    switch (token.type) {
      case "space": return null;
      case "heading": node = createElement(`h${Math.min(6, Math.max(2, token.depth || 2))}`, null, children); break;
      case "paragraph": node = <p>{children}</p>; break;
      case "strong": node = <strong>{children}</strong>; break;
      case "em": node = <em>{children}</em>; break;
      case "del": node = <del>{children}</del>; break;
      case "codespan": node = <code>{token.text}</code>; break;
      case "code": node = <pre tabIndex={0}><code>{token.text}</code></pre>; break;
      case "blockquote": node = <blockquote>{children}</blockquote>; break;
      case "br": node = <br />; break;
      case "hr": node = <hr />; break;
      case "link": node = safeLink(token.href) ? <a href={safeLink(token.href)} rel="noopener noreferrer">{children}</a> : children; break;
      case "image": node = token.text || ""; break;
      case "list": node = createElement(token.ordered ? "ol" : "ul", token.ordered ? { start: token.start } : {},
        token.items?.map((item, itemIndex) => <li key={itemIndex}>
          {item.task ? <input type="checkbox" checked={!!item.checked} disabled aria-label="Task" /> : null}
          {markdownNodes(item.tokens || [])}</li>)); break;
      case "table": node = <div className="intelligence-markdown-table" tabIndex={0} role="region" aria-label="File table"><table>
        <thead><tr>{token.header?.map((cell, cellIndex) => <th key={cellIndex} scope="col">{markdownNodes(cell.tokens || [])}</th>)}</tr></thead>
        <tbody>{token.rows?.map((row, rowIndex) => <tr key={rowIndex}>{row.map((cell, cellIndex) =>
          <td key={cellIndex}>{markdownNodes(cell.tokens || [])}</td>)}</tr>)}</tbody>
      </table></div>; break;
      // Raw HTML remains text. Images cannot make third-party requests from a private file.
      default: node = children;
    }
    return <Fragment key={index}>{node}</Fragment>;
  });
}

export function FileMarkdown({ body, preserveFrontmatter = false }: { body: string; preserveFrontmatter?: boolean }) {
  const content = preserveFrontmatter ? body : body.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "");
  const nodes = useMemo(() => markdownNodes(markdownParser.lexer(content)), [content]);
  return <div className="intelligence-markdown" data-testid="intelligence-markdown">{nodes}</div>;
}

export default function FileView({ path, api, onClose, initialHistory = false, onChanged }: {
  path: string; api: IntelligenceApi; onClose: () => void; initialHistory?: boolean; onChanged?: () => void;
}) {
  const backRef = useRef<HTMLButtonElement>(null);
  const titleId = useId();
  const [file, setFile] = useState<IntelligenceFile | null>(null);
  const [problem, setProblem] = useState("");
  const [missingFile, setMissingFile] = useState(false);
  const [loading, setLoading] = useState(true);
  const [retry, setRetry] = useState(0);
  const [showHistory, setShowHistory] = useState(initialHistory);
  const [restoreBusy, setRestoreBusy] = useState(false);
  const restoring = useRef(false);
  const readRequest = useRef<AbortController | null>(null);
  const noteEditorRef = useRef<HTMLTextAreaElement>(null);
  const saveRequest = useRef<AbortController | null>(null);
  const [draft, setDraft] = useState<{ body: string; version: number } | null>(null);
  const [saveBusy, setSaveBusy] = useState(false);
  const [saveProblem, setSaveProblem] = useState("");
  const [saveConflict, setSaveConflict] = useState(false);
  const [saved, setSaved] = useState(false);
  const [admission, setAdmission] = useState<{
    api: IntelligenceApi; path: string; retry: number; proposal: IntelligenceProposal | null;
  } | null>(null);
  const onProposalsLoaded = useCallback((rows: IntelligenceProposal[] | null) => {
    setAdmission({ api, path, retry, proposal: rows?.find((row) => row.path === path
      && row.baseVersion === 0 && row.status !== "approved") || null });
  }, [api, path, retry]);
  const newProposal = admission?.api === api && admission.path === path && admission.retry === retry
    ? admission.proposal : null;
  const databaseNote = path.startsWith("database-notes/") || file?.section === "database-notes";
  const editing = draft !== null;
  const viewingHistory = showHistory && !databaseNote;
  // A file is a page: focus lands on Back, the control that returns to the folder.
  useEffect(() => { backRef.current?.focus({ preventScroll: true }); }, []);
  useEffect(() => {
    const abort = new AbortController();
    readRequest.current = abort;
    setLoading(true); setProblem(""); setMissingFile(false); setFile(null);
    setDraft(null); setSaveBusy(false); setSaveProblem(""); setSaveConflict(false); setSaved(false);
    void api.readFile(path, abort.signal).then((value) => {
      if (!abort.signal.aborted) setFile(value);
    }).catch((error: unknown) => {
      if (!abort.signal.aborted) {
        setMissingFile(error instanceof IntelligenceApiError && error.status === 404 && error.code === "no_file");
        setProblem(intelligenceProblem(error, "This file could not be read. Try again."));
      }
    }).finally(() => { if (!abort.signal.aborted) setLoading(false); });
    return () => { abort.abort(); saveRequest.current?.abort(); saveRequest.current = null; };
  }, [api, path, retry]);
  useEffect(() => { if (editing) noteEditorRef.current?.focus(); }, [editing]);

  function acceptFile(value: IntelligenceFile) {
    readRequest.current?.abort();
    setFile(value); setProblem(""); setMissingFile(false); setLoading(false); onChanged?.();
  }

  async function saveNote(event: FormEvent) {
    event.preventDefault();
    if (!draft || !file || !databaseNote || file.canEdit !== true || !api.saveFile || saveRequest.current || saveConflict
      || draft.body === file.body) return;
    const abort = new AbortController();
    saveRequest.current = abort;
    setSaveBusy(true); setSaveProblem(""); setSaved(false);
    try {
      const value = await api.saveFile(path, draft.body, draft.version, abort.signal);
      if (abort.signal.aborted || saveRequest.current !== abort) return;
      acceptFile(value); setDraft(null); setSaved(true);
    } catch (error) {
      if (abort.signal.aborted || saveRequest.current !== abort) return;
      const conflict = error instanceof IntelligenceApiError && error.code === "version_conflict";
      setSaveConflict(conflict);
      setSaveProblem(conflict ? "The note changed. Reload before editing." : intelligenceProblem(error, "The note could not be saved. Try again."));
    } finally {
      if (!abort.signal.aborted && saveRequest.current === abort) { saveRequest.current = null; setSaveBusy(false); }
    }
  }

  function cancelEdit() {
    setDraft(null); setSaveProblem(""); setSaved(false);
    if (saveConflict) setRetry((value) => value + 1);
    setSaveConflict(false);
  }

  return <section className="intelligence-file-page" aria-labelledby={titleId}
      data-testid="intelligence-file" aria-busy={loading || saveBusy}>
      <header className="home-section-head intelligence-file-head">
        <button ref={backRef} type="button" className="cg-btn" data-file-close aria-label="Back" title="Back"
          disabled={restoreBusy || saveBusy} onClick={onClose}>
          <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon" fill="none" stroke="currentColor">
            <path d="M10 3 5 8l5 5" />
          </svg>
        </button>
        <h1 id={titleId} className="home-title">{file?.title || newProposal?.title || "File"}</h1>
      </header>
      {loading ? <div className="intelligence-skeleton" role="status" aria-label="Loading file"><span /><span /><span /></div> : null}
      {problem && !(missingFile && newProposal) ? <div className="intelligence-feedback" role="alert"><span>{problem}</span>
        <button type="button" className="intelligence-button" onClick={() => setRetry((value) => value + 1)}>Retry</button></div> : null}
      {!databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="File view">
        <button type="button" className="intelligence-button" disabled={restoreBusy} aria-pressed={!showHistory} onClick={() => setShowHistory(false)}>File</button>
        <button type="button" className="intelligence-button" disabled={restoreBusy} aria-pressed={showHistory} onClick={() => setShowHistory(true)}>History</button>
      </div> : null}
      {viewingHistory ? <History path={path} api={api} revision={file?.version || 0}
        onBusy={(busy) => { restoring.current = busy; setRestoreBusy(busy); }}
        onRestored={acceptFile} /> : <>
      <Proposals key={path} path={path} api={api} onApproved={acceptFile} onLoaded={onProposalsLoaded} />
      {file ? <>
        {databaseNote ? <div className="intelligence-view-switch" role="group" aria-label="Database note">
          {file.databaseKey ? <a className="intelligence-button" href={`#/data?database=${encodeURIComponent(file.databaseKey)}`}>Open database</a> : null}
          {file.canEdit === true && api.saveFile && !editing ? <button type="button" className="intelligence-button"
            onClick={() => { setDraft({ body: file.body, version: file.version }); setSaveProblem(""); setSaved(false); }}>Edit</button> : null}
        </div> : null}
        {databaseNote && draft ? <form className="intelligence-create" aria-busy={saveBusy} onSubmit={(event) => void saveNote(event)}>
          <label>Note<textarea ref={noteEditorRef} value={draft.body} disabled={saveBusy} rows={12}
            onChange={(event) => { const body = event.target.value; setDraft((current) => current ? { ...current, body } : null); }} /></label>
          {saveProblem ? <div className="intelligence-feedback" role="alert"><span>{saveProblem}</span>
            <button className="intelligence-button" type="button" disabled={saveBusy} onClick={() => setRetry((value) => value + 1)}>Reload</button></div> : null}
          <div className="intelligence-create-actions">
            <button className="intelligence-button" type="button" disabled={saveBusy} onClick={cancelEdit}>Cancel</button>
            <button className="intelligence-button intelligence-primary" type="submit"
              disabled={saveBusy || saveConflict || file.canEdit !== true || !api.saveFile || draft.body === file.body}>{saveBusy ? "Saving…" : "Save"}</button>
          </div>
        </form> : file.section === "agent-prompts"
        ? <PromptView tools={file.resolvedTools || []}><FileMarkdown body={file.body} /></PromptView>
        : <FileMarkdown body={file.body} preserveFrontmatter={databaseNote} />}
        {saved ? <p className="intelligence-meta" role="status">Saved.</p> : null}
        <footer className="intelligence-file-by" data-testid="intelligence-version">
          {databaseNote ? <div>History is in Notes</div> : null}
          <div>Version {file.version} · Last changed by {file.author}{file.onBehalfOf ? ` for ${file.onBehalfOf}` : ""}</div>
          {file.approvedBy?.length ? <div>Approved by {file.approvedBy.join(", ")}</div> : null}
          {file.restoredFrom ? <div>Restored from version {file.restoredFrom}</div> : null}
          <time dateTime={file.updated}>{fileDate(file.updated)}</time>
        </footer>
      </> : null}</>}
    </section>;
}