// A project on the database page — its description and conversation, drawn // under the page's head; its sections are tiles on the page's grid. A project has no screen of its own: // its page is the database page with that project chosen, `/projects` is the // project table's list, and its brand is its database's own record page // (`DatabaseBrand`). // // THE THREE-STATE SLUG IS THE INVARIANT. A project read has three answers, not // two: not read yet, read and ABSENT, and here. Collapsing them tells somebody // their project does not exist when the truth is that the file could not be // opened: `PaperReadBody` separates the refusal from the answer, and this adds // the third — an answer that arrived and holds no project. // import CottonKit import SwiftUI // MARK: - A project on the database page /// A project's own part of the database page: its description slip and its /// conversation, drawn under the page's head. There /// is no screen of its own any more — the database page is the project's /// page — so it has no cap at the top (the head says the name) and no frame. struct ProjectPageBody: View { let read: ScreenRead /// This screen's writes. `ScreenRead` answers one bound writer whose /// fallback re-read is that read's own `load()`. private var writer: ScreenWriter { read.writer } @Environment(\.theme) private var theme @State private var menuOpen = false @State private var confirmArchive = false /// The one editor, reached two ways (Rename and Repos), exactly as the /// Expo kebab reached one sheet from two rows. @State private var editing = false @State private var draftName = "" @State private var draftSummary = "" @State private var draftRepos = "" /// Whether the description's slip is open. The page's own state and /// nothing else's: folding is a way of reading, not a fact about the /// project, so it is not remembered between visits. @State private var summaryOpen = false /// The conversation is being opened for its first message. @State private var starting = false /// The conversation this page talks to, opened once and kept /// (`ProjectConversationModel`). @State private var conversation = ProjectConversationModel() /// `read.session` for that conversation — the SECOND read this page /// mounts, built off the first one (`ScreenRead.following`) as soon as /// `read.project` names an id, and re-read with it from then on. @State private var conversationRead: ScreenRead? private let slug: String @Environment(Navigator.self) private var navigator /// Archiving leaves the project: the page goes back to the database's own. private let onLeave: () -> Void /// Read ONCE, at the screen's own birth, and threaded into every date on /// it — the same `useMemo(() => new Date(), [])` the Expo page kept, and /// the reason no view body here calls a clock. private let now: Date @Environment(\.pageMenu) private var pageMenu @Environment(ToastCenter.self) private var toasts init( read: ScreenRead, slug: String, now: Date = Date(), onLeave: @escaping () -> Void = {} ) { self.read = read self.slug = slug self.now = now self.onLeave = onLeave } var body: some View { PaperReadBody(read: read) { answer in let project = answer["project"] ?? .null if project == .null { QuietState( title: CottonStrings.noProjectCalled(slug), message: CottonStrings.projectSlugNeverChanges ) } else { page(project, answer: answer) } } .menuTray(isOpen: $menuOpen, items: menu()) .confirmDecision( isPresented: $confirmArchive, title: ShellLines.line("projects", "archive_this_project"), message: ShellLines.line("projects", "it_leaves_your_lists"), confirmLabel: "Archive", identifier: "project-archive", onConfirm: { setStatus("archived", say: "Archived", thenLeave: true) } ) .cottonCard(isPresented: $editing) { editSheet } } /// `update_project` is addressed by SLUG — the tool has no `id` property, /// and `list_projects` answers none either. The slug is this screen's own /// route parameter, so it is always in hand. private func setStatus(_ status: String, say: String, thenLeave: Bool) { Task { if await writer.run( "update_project", ["slug": .string(slug), "status": .string(status)] ) { toasts.show(say, tone: .success) if thenLeave { onLeave() } } else if let refusal = writer.refusal { toasts.show(refusal, tone: .error) } } } // MARK: The page /// The description on a slip of its own, with the page's stack button beside it, and /// the conversation — its last exchanges, or Start the conversation. What /// the project's sections held are tiles on the database page now /// (architect, 13 Oct 2026: nothing on the database page draws a list of /// rows), each a view `project/
/` placed by the board. @ViewBuilder private func page(_ project: JSONValue, answer: JSONValue) -> some View { VStack(alignment: .leading, spacing: 24) { // The description, with the page's stack button beside it (Edit, Archive) // now that no screen frame carries it. HStack(alignment: .top, spacing: 10) { summary(project) TrayStackButton { // On the database page the page holds the tray up, so it // covers the whole page. if let pageMenu { pageMenu.open(menu()) } else { menuOpen = true } } .accessibilityIdentifier("project-menu") } // The project's conversation, its last exchanges first (Cotton note // "The project conversation — one standing thread per project"). // Its composer went with the UI direction (0a22168c §2): the // bottom bar does that job, and the conversation's own page // (`Open the conversation`, or `Start the conversation` before // there is one) is where a message to it is typed. transcript(answer) } } /// The summary, on a slip of its own — the description IS the summary /// (R80), so the page gives it the same object every record on the page /// gets: a full-width slip, the paragraph typed on it, clamped to four /// lines with the tail ellipsis. /// /// **A TAP OPENS IT IN PLACE, it no longer opens the editor.** Reading a /// long description used to mean opening a text field over it, which is /// the wrong verb for reading; editing is the tray's Edit, which opens /// the same one sheet it always did. A description short enough to fit /// does not fold, so no tap on the page does nothing (`SlipFold.folds`). /// /// A project nobody has described keeps the hint in pencil, and THAT still /// opens the editor — it is the only way in for a fresh project, since /// `get_project` omits the key entirely when there is no summary. @ViewBuilder private func summary(_ project: JSONValue) -> some View { let text = project["summary"]?.text("text")?.trimmingCharacters(in: .whitespacesAndNewlines) if let text, !text.isEmpty { let folds = SlipFold.folds( text, clamp: ProjectOnBoardKnobs.paperSlipSummaryLines, lineWidth: ProjectOnBoardKnobs.paperSlipLineWidthCharacters) let slip = ObjectSlip( seed: "\(slug)-summary", dye: .cream, prose: text, clamp: ProjectOnBoardKnobs.paperSlipSummaryLines, expanded: summaryOpen || !folds ) if folds { Button { summaryOpen.toggle() } label: { slip } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("project-summary") .accessibilityHint(summaryOpen ? ShellLines.line("projects", "folds_the_description") : ShellLines.line("projects", "opens_the_whole_description")) } else { slip.accessibilityIdentifier("project-summary") } } else { Button { openEditor(project) } label: { Text(ShellLines.line("projects", "add_a_summary_what")) .paperMeta(13) .frame(maxWidth: .infinity, alignment: .leading) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("project-summary") } } // MARK: The conversation /// The last exchanges, drawn with the session page's own transcript /// (`SessionTranscript`) so the two cannot disagree about what a turn /// looks like. /// /// **A PROJECT WITH NO CONVERSATION SAYS SO IN ONE LINE.** Nothing has /// gone wrong — nobody has said anything yet — and the composer above is /// the answer, so the line names it rather than offering a second button. /// A conversation that exists and has said nothing yet draws nothing: the /// row is there, the transcript is empty, and a sentence about an empty /// transcript is a sentence about nothing. /// /// There is NO answer field on this page: a question a thread addressed to /// the owner is answered on that thread's own page, which its card opens. @ViewBuilder private func transcript(_ answer: JSONValue) -> some View { if let plan = ProjectThreads.conversationRead(answer) { VStack(alignment: .leading, spacing: 10) { // A conversation that never started says so, above whatever // was said to it — otherwise the message below reads as // waiting for a reply that is not coming. if let failure = ProjectThreads.conversationFailure(answer) { Text(failure) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .accessibilityIdentifier("project-conversation-failed") } exchanges // ALWAYS, not only when the transcript was cut: the standing // conversation has a page of its own — its task list, its // whole history, the verbs — and the composer above is the // only other way in. Button { navigator.push(.sessionsId(id: plan.id)) } label: { Text(ProjectThreads.openConversation) .paperMeta(13) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("project-conversation-open") } // Built ONCE, and only once there is an id to give it. Rebuilding // it on every redraw would put a second read on the first one's // list at every frame. .task(id: plan.id) { if conversationRead == nil { conversationRead = read.following( read: plan.name, args: plan.args, families: plan.families ) } await conversationRead?.set("id", .string(plan.id)) } } else { // Nothing has been said yet: the one way in opens the // conversation (`project.conversation` ensures its row) on its own // page, whose composer takes the first message. Button { startConversation() } label: { Text(ProjectThreads.startConversation) .paperMeta(13) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .disabled(starting) .accessibilityIdentifier("project-conversation-start") } } /// The conversation's own exchanges, off the second read. /// /// Nothing at all while that read is in flight or has refused: the page /// under it is whole, and a sentence about a transcript that has not /// arrived yet is a sentence about nothing. The composer above works /// either way — a message is sent to an id, not to a transcript. @ViewBuilder private var exchanges: some View { if let row = conversationRead?.value?["session"], row != .null { SessionTranscript( session: row, messages: conversationRead?.value?.list("messages") ?? [], turns: conversationRead?.value?.list("prompts") ?? [], limit: ProjectThreads.conversationLimit ) .accessibilityIdentifier("project-conversation-transcript") } } /// Say it to the project. /// /// The conversation is opened ONCE — `project.conversation` ensures the /// row and is idempotent, so the id is kept for as long as this page is on /// screen — and then its page is pushed, which reads as the conversation's /// history: Cotton sends nothing to a session. private func startConversation() { starting = true Task { defer { starting = false } do { let target = try await conversation.resolve( known: ProjectThreads.conversationId(read.value ?? .null) ) { let opened = try await writer.call( "project.conversation", ProjectConversationRequest(slug: slug) ) guard let id = opened.text("id") else { throw CottonCallError( code: "no-conversation", message: ShellLines.line("projects", "this_project_s_conversation") ) } return id } await read.load() navigator.push(.sessionsId(id: target)) } catch let error as CottonCallError { toasts.show(error.message, tone: .error) } catch { toasts.show(String(describing: error), tone: .error) } } } /// Edit opens the one sheet that holds the name, the summary AND the /// repositories (a second "Repos" item opening the same sheet was retired /// in phase 28). **It is now the only way to the description**: the /// paragraph on the page is a slip a tap opens for READING, and editing a /// described project belongs in the menu with the project's other verbs. /// Archiving is undoable and Restore sits in the same slot, so the menu /// never offers a verb the project's state has taken. /// /// The two SHARE verbs the Expo kebab also carried are not here: sharing a /// project with someone is not a verb this lane ported. Owed back. private func menu() -> [PopoverMenuItem] { let project = read.value?["project"] ?? .null guard project != .null else { return [] } let archived = project.text("status") == "archived" var items: [PopoverMenuItem] = [ PopoverMenuItem(id: "edit", object: CardEnamel.edit.rawValue, does: nil, label: ShellLines.line("projects", "edit")) { menuOpen = false openEditor(project) }, ] if archived { items.append( PopoverMenuItem( id: "restore", label: ShellLines.line("projects", "restore_this_project") ) { menuOpen = false // Restore stays put rather than popping: you asked for this // project back, so you are left looking at it. setStatus("active", say: ShellLines.line("projects", "back_on"), thenLeave: false) } ) } else { items.append( PopoverMenuItem( id: "archive", label: ShellLines.line("projects", "archive_project"), destructive: true ) { menuOpen = false confirmArchive = true } ) } return items } /// Seed the editor from the ANSWER, every time it opens — a draft left /// over from a previous opening would put stale prose over newer words. private func openEditor(_ project: JSONValue) { draftName = project.text("name") ?? "" draftSummary = project["summary"]?.text("text") ?? "" draftRepos = project.strings("repos").joined(separator: "\n") editing = true } /// The project editor — name, Summary and repos, saved in ONE call. /// /// The Expo sheet needed two writers because the TS service could not move /// a description (R90); `update_project` takes all three, and it is the /// tool that decides whether the summary stamp moves (`summary_patch_for`) /// — so re-saving a paragraph nobody edited re-dates nothing. /// /// **Summary** is `cotton_memory_projects.description`, labelled Summary /// wherever a person reads it. The SLUG never moves: it is minted at birth /// and it is what every briefing cites. @ViewBuilder private var editSheet: some View { VStack(alignment: .leading, spacing: 12) { Text(ShellLines.line("projects", "edit_project")).cottonType(.screenTitle) Text(ShellLines.line("projects", "code_sessions_working_in")).cottonType(.preview, ink: .secondary) TextField(ShellLines.line("projects", "project_name"), text: $draftName) .cottonType(.body) .textFieldStyle(.plain) .padding(.vertical, 10) TextField( ShellLines.line("projects", "what_this_project_is"), text: $draftSummary, axis: .vertical ) .cottonType(.body) .textFieldStyle(.plain) .lineLimit(3...8) .padding(.vertical, 10) TextField(ShellLines.line("projects", "git_remotes_one_per"), text: $draftRepos, axis: .vertical) .cottonType(.body) .textFieldStyle(.plain) .lineLimit(2...6) .autocorrectionDisabled() .textInputAutocapitalization(.never) .padding(.vertical, 10) Text(ShellLines.line("projects", "briefings_address_it_as", ["slug": "\(slug)"])).cottonType(.caption, ink: .tertiary) Button { save() } label: { Text(writer.busy ? CottonStrings.savingLabel : CottonStrings.saveLabel) .cottonType(.body, ink: .inverse, weight: .semibold) .frame(maxWidth: .infinity) .padding(.vertical, 14) .background(Capsule().fill(CottonColors.accent)) } .buttonStyle(MotionButtonStyle()) .disabled( writer.busy || draftName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ) } .cottonContentMargin() .padding(.vertical, 20) } private func save() { let name = draftName.trimmingCharacters(in: .whitespacesAndNewlines) guard !name.isEmpty else { return } // A cleared summary is the EMPTY STRING, which is how `update_project` // spells "clear it" — the column's absence and an empty paragraph are // the same fact, and only one of them reads well in a briefing. let summary = draftSummary.trimmingCharacters(in: .whitespacesAndNewlines) let repos = draftRepos .split(separator: "\n") .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } Task { if await writer.run( "update_project", [ "slug": .string(slug), "name": .string(name), "description": .string(summary), "repos": .array(repos.map { .string($0) }), ] ) { editing = false } else if let refusal = writer.refusal { toasts.show(refusal, tone: .error) } } } } /// The project a database page shows, read and drawn under the page's head. struct ProjectOnBoard: View { let slug: String let onLeave: () -> Void var body: some View { Hosted({ core, _ in // `.sessions` because the page draws the project's conversation // and the threads under it. ScreenRead(core: core, read: "project", args: ["slug": .string(slug)], families: [.projects, .core, .summary, .sessions]) }) { read in ProjectPageBody(read: read, slug: slug, onLeave: onLeave) } .id(slug) } } /// The sizes, counts and timings ProjectOnBoard draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum ProjectOnBoardKnobs { static let paperSlipLineWidthCharacters = 45 static let paperSlipSummaryLines = 4 }