Something went wrong. Try again.
Sensemaker's home repository for public resources.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402import React, { useEffect, useMemo, useState } from "react"import { createRoot } from "react-dom/client"import "./styles.css"
type SessionRecord = { $type: "network.sensemaker.session" title: string subject: string interviewer: string topic?: string introduction?: string mode?: "closed" | "open" status?: "open" | "closed" createdAt: string}
type QuestionRecord = { $type: "network.sensemaker.question" text: string subject: string session?: string topic?: string inReplyTo?: string context?: string createdAt: string}
type AnswerRecord = { $type: "network.sensemaker.answer" text: string question: string sources?: string[] createdAt: string}
type RepoRecord<T> = { uri: string; cid: string; value: T }type Interview = { sessionUri: string session: SessionRecord questions: Array<RepoRecord<QuestionRecord>> answers: Array<RepoRecord<AnswerRecord>>}
type AppConfig = { oauth?: { enabled: boolean clientMetadataUrl: string callbackUrl: string reason?: string }}
const DEFAULT_SESSION = "at://did:plc:4j7exarb62djxycrgdfhuulr/network.sensemaker.session/3mmet7dmrel2h"const DEFAULT_INTERVIEWER = "did:plc:4j7exarb62djxycrgdfhuulr"const COLLECTIONS = { session: "network.sensemaker.session", question: "network.sensemaker.question", answer: "network.sensemaker.answer",} as const
function parseAtUri(uri: string): { did: string; collection: string; rkey: string } { const match = uri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/) if (!match) throw new Error(`Invalid AT-URI: ${uri}`) return { did: match[1], collection: match[2], rkey: match[3] }}
async function resolveHandle(input: string): Promise<string> { if (input.startsWith("did:")) return input const handle = input.replace(/^@/, "") const res = await fetch(`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`) if (!res.ok) throw new Error(`Could not resolve handle ${handle}`) const data = await res.json() as { did: string } return data.did}
async function resolvePds(did: string): Promise<string> { if (did.startsWith("did:plc:")) { const res = await fetch(`https://plc.directory/${did}`) if (!res.ok) throw new Error(`PLC lookup failed for ${did}`) const doc = await res.json() as { service?: Array<{ id: string; serviceEndpoint: string }> } const service = doc.service?.find((s) => s.id === "#atproto_pds") if (!service) throw new Error(`No PDS service in DID document for ${did}`) return service.serviceEndpoint } if (did.startsWith("did:web:")) { const host = did.slice("did:web:".length) const res = await fetch(`https://${host}/.well-known/did.json`) if (!res.ok) throw new Error(`did:web lookup failed for ${did}`) const doc = await res.json() as { service?: Array<{ id: string; serviceEndpoint: string }> } const service = doc.service?.find((s) => s.id.endsWith("atproto_pds")) if (!service) throw new Error(`No PDS service in DID document for ${did}`) return service.serviceEndpoint } throw new Error(`Unsupported DID method: ${did}`)}
async function getRecord<T>(pds: string, did: string, collection: string, rkey: string): Promise<RepoRecord<T>> { const params = new URLSearchParams({ repo: did, collection, rkey }) const res = await fetch(`${pds}/xrpc/com.atproto.repo.getRecord?${params}`) if (!res.ok) throw new Error(`Record not found: ${collection}/${rkey}`) return await res.json() as RepoRecord<T>}
async function listRecords<T>(pds: string, did: string, collection: string, limit = 100): Promise<Array<RepoRecord<T>>> { const all: Array<RepoRecord<T>> = [] let cursor: string | undefined do { const params = new URLSearchParams({ repo: did, collection, limit: String(limit) }) if (cursor) params.set("cursor", cursor) const res = await fetch(`${pds}/xrpc/com.atproto.repo.listRecords?${params}`) if (!res.ok) throw new Error(`Could not list ${collection} on ${did}`) const data = await res.json() as { records: Array<RepoRecord<T>>; cursor?: string } all.push(...data.records) cursor = data.cursor } while (cursor && all.length < 500) return all}
async function loadInterview(sessionUri: string): Promise<Interview> { const parsed = parseAtUri(sessionUri) if (parsed.collection !== COLLECTIONS.session) throw new Error("URI is not an interview session")
const interviewerPds = await resolvePds(parsed.did) const sessionRecord = await getRecord<SessionRecord>(interviewerPds, parsed.did, parsed.collection, parsed.rkey) const session = sessionRecord.value
const questions = (await listRecords<QuestionRecord>(interviewerPds, parsed.did, COLLECTIONS.question)) .filter((record) => record.value.session === sessionUri) .sort((a, b) => a.value.createdAt.localeCompare(b.value.createdAt))
const subjectPds = await resolvePds(session.subject) const questionSet = new Set(questions.map((q) => q.uri)) const answers = (await listRecords<AnswerRecord>(subjectPds, session.subject, COLLECTIONS.answer)) .filter((record) => questionSet.has(record.value.question)) .sort((a, b) => a.value.createdAt.localeCompare(b.value.createdAt))
return { sessionUri, session, questions, answers }}
async function loadSessions(repo: string): Promise<Array<RepoRecord<SessionRecord>>> { const did = await resolveHandle(repo) const pds = await resolvePds(did) return (await listRecords<SessionRecord>(pds, did, COLLECTIONS.session)) .sort((a, b) => b.value.createdAt.localeCompare(a.value.createdAt))}
function formatDate(value: string): string { return new Intl.DateTimeFormat("en", { month: "long", day: "numeric", year: "numeric" }).format(new Date(value))}
function shortDid(did: string): string { return did.replace(/^did:plc:/, "did:plc:").slice(0, 18) + "…"}
function atUriToBsky(uri: string): string | null { try { const { did, collection, rkey } = parseAtUri(uri) if (collection !== "app.bsky.feed.post") return null return `https://bsky.app/profile/${did}/post/${rkey}` } catch { return null }}
function createAnswerRecord(questionUri: string, text: string): AnswerRecord { return { $type: "network.sensemaker.answer", question: questionUri, text, createdAt: new Date().toISOString(), }}
function AnswerComposer({ questionUri }: { questionUri: string }) { const [text, setText] = useState("") const answerRecord = createAnswerRecord(questionUri, text) const record = JSON.stringify(answerRecord, null, 2) const body = JSON.stringify({ repo: "YOUR_DID", collection: COLLECTIONS.answer, record: answerRecord }, null, 2) const curl = `curl -X POST "https://YOUR_PDS/xrpc/com.atproto.repo.createRecord" \\ -H "Authorization: Bearer YOUR_ACCESS_JWT" \\ -H "Content-Type: application/json" \\ -d '${body.replace(/'/g, "'\\''")}'`
async function copy(value: string) { await navigator.clipboard?.writeText(value) }
return ( <div className="composer"> <p className="label">Answer this question</p> <textarea value={text} onChange={(event) => setText(event.target.value)} placeholder="Draft an answer. Sign-in writing is next; for now this creates the ATProto record payload." /> <div className="composer-actions"> <button type="button" onClick={() => copy(record)}>Copy record JSON</button> <button type="button" onClick={() => copy(curl)}>Copy XRPC curl</button> </div> <details> <summary>Preview record</summary> <pre>{record}</pre> </details> </div> )}
async function loadConfig(): Promise<AppConfig | null> { try { const res = await fetch("/api/config") if (!res.ok) return null return await res.json() as AppConfig } catch { return null }}
function InterviewPage() { const params = new URLSearchParams(window.location.search) const [input, setInput] = useState(params.get("session") ?? DEFAULT_SESSION) const [sessionUri, setSessionUri] = useState(input) const [repoInput, setRepoInput] = useState(params.get("repo") ?? DEFAULT_INTERVIEWER) const [view, setView] = useState<"interview" | "index">(params.get("view") === "index" ? "index" : "interview") const [data, setData] = useState<Interview | null>(null) const [sessions, setSessions] = useState<Array<RepoRecord<SessionRecord>>>([]) const [error, setError] = useState<string | null>(null) const [loading, setLoading] = useState(false) const [config, setConfig] = useState<AppConfig | null>(null)
useEffect(() => { loadConfig().then(setConfig) }, [])
useEffect(() => { if (view !== "interview") return let alive = true setLoading(true) setError(null) loadInterview(sessionUri) .then((interview) => { if (alive) setData(interview) }) .catch((err) => { if (alive) setError(err instanceof Error ? err.message : String(err)) }) .finally(() => { if (alive) setLoading(false) }) return () => { alive = false } }, [sessionUri, view])
useEffect(() => { if (view !== "index") return let alive = true setLoading(true) setError(null) loadSessions(repoInput) .then((records) => { if (alive) setSessions(records) }) .catch((err) => { if (alive) setError(err instanceof Error ? err.message : String(err)) }) .finally(() => { if (alive) setLoading(false) }) return () => { alive = false } }, [repoInput, view])
const answerByQuestion = useMemo(() => { const map = new Map<string, RepoRecord<AnswerRecord>>() for (const answer of data?.answers ?? []) map.set(answer.value.question, answer) return map }, [data])
function loadSession(event?: React.FormEvent, nextUri = input.trim()) { event?.preventDefault() if (!nextUri) return const url = new URL(window.location.href) url.searchParams.set("session", nextUri) url.searchParams.set("view", "interview") window.history.replaceState({}, "", url) setInput(nextUri) setSessionUri(nextUri) setView("interview") }
function loadIndex(event?: React.FormEvent) { event?.preventDefault() const url = new URL(window.location.href) url.searchParams.set("repo", repoInput) url.searchParams.set("view", "index") window.history.replaceState({}, "", url) setView("index") }
return ( <main> <header className="site-header"> <div> <p className="eyebrow">Interviewer</p> <h1>{view === "index" ? "Interviewer" : (data?.session.title ?? "Interviewer")}</h1> <p className="dek">{view === "index" ? "Browse interview sessions written as ATProto records." : "ATProto-native Q&A rendered as a quiet public record."}</p> </div> <img className="brand-logo" src="/logo.svg" alt="Sensemaker" /> </header>
<nav className="tabs" aria-label="Interview views"> <button className={view === "interview" ? "active" : ""} onClick={() => loadSession(undefined, sessionUri)}>Interview</button> <button className={view === "index" ? "active" : ""} onClick={() => loadIndex()}>Sessions</button> </nav>
{view === "interview" ? ( <form className="loader" onSubmit={(event) => loadSession(event)}> <label htmlFor="session">Session AT-URI</label> <div> <input id="session" value={input} onChange={(event) => setInput(event.target.value)} /> <button type="submit">Load</button> </div> </form> ) : ( <form className="loader compact-loader" onSubmit={(event) => loadIndex(event)}> <label htmlFor="repo">Interviewer repo</label> <div> <input id="repo" value={repoInput} onChange={(event) => setRepoInput(event.target.value)} /> <button type="submit">List</button> </div> </form> )}
{loading && <p className="status">Loading from ATProto PDSes…</p>} {error && <p className="error">{error}</p>}
{view === "index" && !loading && !error && ( <section className="session-list"> {sessions.map((session) => ( <article className="session-row" key={session.uri}> <div> <p className="eyebrow">{session.value.mode === "open" ? "Open survey" : (session.value.topic ?? "Interview")}</p> <h2>{session.value.title}</h2> <p>{session.value.introduction ?? "ATProto-native interview session."}</p> <p className="uri"><code>{session.uri}</code></p> </div> <button onClick={() => loadSession(undefined, session.uri)}>View</button> </article> ))} {sessions.length === 0 && <p className="status">No interview sessions found.</p>} </section> )}
{view === "interview" && data && !loading && ( <article className="interview"> <section className="meta-card"> <dl> <div><dt>Session</dt><dd><code>{data.sessionUri}</code></dd></div> <div><dt>Subject</dt><dd>{shortDid(data.session.subject)}</dd></div> <div><dt>Interviewer</dt><dd>{shortDid(data.session.interviewer)}</dd></div> <div><dt>Created</dt><dd>{formatDate(data.session.createdAt)}</dd></div> <div><dt>Status</dt><dd>{data.answers.length}/{data.questions.length} answered</dd></div> <div><dt>Mode</dt><dd>{data.session.mode === "open" ? "Open survey" : "Closed interview"}</dd></div> </dl> {data.session.introduction && <p>{data.session.introduction}</p>} </section>
<section className="write-card"> <div> <p className="label">Writing answers</p> <h2>Sign-in answering is the next protocol step.</h2> <p>ATProto OAuth is the right write path: authorization code flow, PKCE, DPoP, and a public client metadata URL. This app does not ask for app passwords. Until OAuth is wired, unanswered questions expose a safe answer-record payload and XRPC template.</p> {config?.oauth && ( <p className="oauth-note">OAuth metadata: <code>{config.oauth.clientMetadataUrl}</code>. Status: {config.oauth.enabled ? "enabled" : "metadata only"}.</p> )} </div> </section>
<section className="qa-list"> {data.questions.map((question, index) => { const answer = answerByQuestion.get(question.uri) const answerLink = answer ? atUriToBsky(answer.uri) : null return ( <section className="qa" key={question.uri}> <div className="number">{String(index + 1).padStart(2, "0")}</div> <div className="content"> <p className="label">Question</p> <p className="question">{question.value.text}</p> {question.value.context && <p className="context">{question.value.context}</p>} <p className="uri"><code>{question.uri}</code></p>
{answer ? ( <div className="answer-block"> <p className="label">Answer</p> {answer.value.text.split(/\n\n+/).map((paragraph, i) => <p key={i}>{paragraph}</p>)} {answer.value.sources && answer.value.sources.length > 0 && ( <ul className="sources"> {answer.value.sources.map((source) => <li key={source}><a href={source}>{source}</a></li>)} </ul> )} <p className="uri"><code>{answer.uri}</code>{answerLink && <> · <a href={answerLink}>view post</a></>}</p> </div> ) : ( <> <p className="pending">No answer record yet.</p> <AnswerComposer questionUri={question.uri} /> </> )} </div> </section> ) })} </section> </article> )} </main> )}
createRoot(document.getElementById("root")!).render(<InterviewPage />)