This document is the canonical placement map for production and test source files. It complements
ARCHITECTURE.md, which explains runtime ownership and data flow.
Swift folders do not create namespaces. Every Swift file discovered under Cotabby/ still compiles
into the application module, and every file under CotabbyTests/ compiles into the test module.
Folders exist so a maintainer can predict where a responsibility lives before searching.
- Choose the top-level architectural boundary first:
App,UI,Services,Models, orSupport. - Choose the product subsystem next, such as
Suggestion,Focus,Runtime, orSettings. - Keep a small cohesive subsystem flat.
- Add a child folder only when at least two files form a stable responsibility with a predictable name. Do not create one-file folders merely to shorten a file list.
- Put a direct unit test under the corresponding
CotabbyTests/responsibility. Cross-cutting coordinator tests may remain grouped by the coordinator they exercise. - Folder moves must not change Swift access control, runtime ownership, or target membership.
XcodeGen discovers the new paths; regenerate
Cotabby.xcodeprojafter moving files.
Cotabby/
├── App/
│ ├── Core/ process entry, composition root, lifecycle
│ └── Coordinators/
│ ├── InlineFeatures/ emoji/macro capture arbitration
│ ├── Suggestion/ autocomplete interaction state machine
│ ├── SettingsCoordinator.swift
│ └── WelcomeCoordinator.swift
├── Models/
│ ├── Context/ bounded context and visual-context values
│ ├── Emoji/ picker values and the persisted usage store
│ ├── Focus/ focus snapshots and tracking state
│ ├── History/ typing-history records, archive, and preferences
│ ├── Input/ keyboard event values
│ ├── Onboarding/ onboarding templates
│ ├── Permissions/ TCC permission values
│ ├── Runtime/
│ │ └── Metrics/ performance and system metric stores
│ ├── Settings/ durable and UI-facing settings values
│ ├── Spelling/ spelling catalog values
│ └── Suggestion/
│ ├── Request/ immutable request inputs and configuration
│ ├── Result/ engine result and client error values
│ └── Session/ active, paused, and presented session values
├── Services/
│ ├── Context/ live clipboard acquisition
│ ├── Focus/
│ │ ├── Caching/ field-scoped focus caches
│ │ ├── Chromium/ Chromium AX enablement and diagnostics
│ │ └── Resolution/ focus snapshots, geometry, bounded AX walks
│ ├── History/ typing-history store, recording, and encrypted vault
│ ├── Input/ event taps and input-source monitoring
│ ├── ModelManagement/ model discovery, download, and validation
│ ├── Permission/
│ │ └── Guidance/ permission overlay and System Settings guidance
│ ├── Power/ power-source observation
│ ├── Presentation/ process-level AppKit panels and indicators
│ ├── Runtime/
│ │ ├── AppleIntelligence/ Foundation Models availability and engine
│ │ ├── Llama/ llama engine, manager, and native core
│ │ └── OpenAICompatible/ endpoint transport, credentials, and engine
│ ├── Spelling/ live spell-checking services
│ ├── Suggestion/
│ │ └── State/ work identity and mutable interaction state
│ ├── Updates/ manual release checks
│ └── Visual/ capture, OCR, and visual-context sessions
├── Support/
│ ├── Accessibility/ pure AX and secure-surface policies
│ ├── Context/ sanitization, relevance, and OCR hygiene
│ ├── Emoji/
│ │ ├── Catalog/ searchable catalog and synonyms
│ │ ├── Interaction/ query, trigger, picker, and variant rules
│ │ └── Ranking/ recency and popularity rules
│ ├── Focus/
│ │ ├── Applications/ app, browser, domain, and terminal classification
│ │ └── Capability/ supported-field capability resolution
│ ├── History/ history retrieval, phrase prediction, scrubbing, import
│ ├── InlineCommands/ key and focus rules shared by emoji and macro capture
│ ├── Input/ composition, key-label, and selection helpers
│ ├── Logging/ debug options, request IDs, and JSONL handlers
│ ├── Macros/
│ │ └── Evaluators/ deterministic arithmetic/date/unit evaluators
│ ├── Onboarding/ flow steps, recommendation rules, inline-prediction nudge
│ ├── Presentation/
│ │ ├── Geometry/ caret, anchor, direction, and overlay layout
│ │ ├── Policy/ render-mode, fade, and stability decisions
│ │ └── Style/ ghost text font and color rules
│ ├── Prompting/ Apple and base-model prompt rendering
│ ├── Runtime/
│ │ ├── Hardware/ device capability and resource sampling
│ │ ├── BundledRuntimeLocator.swift
│ │ ├── DecodeStopPolicy.swift
│ │ ├── DownloadOutcomeClassifier.swift
│ │ ├── LocalRuntimeResidencyPolicy.swift when the local model stays loaded
│ │ ├── TokenHealingPlan.swift bounded word-fragment retokenization at the caret
│ │ └── TokenHealingBuffer.swift exact byte replay and lossless streamed UTF-8
│ ├── Settings/ persistence and settings policies
│ ├── Spelling/ extraction, language, SymSpell, and typo rules
│ ├── Suggestion/
│ │ ├── Acceptance/ insertion safety and strategy
│ │ ├── Output/ normalization, confidence, and seam cleanup
│ │ ├── Request/ availability, debounce, and request construction
│ │ ├── Session/ tail reconciliation and exhausted-tail state
│ │ └── Streaming/ partial coalescing, monotonic text, presentation timing
│ └── Utilities/ small cross-subsystem value helpers
└── UI/
├── Components/ application-wide reusable views
├── InlineFeatures/ emoji picker and macro reference surfaces
├── MenuBar/ menu-bar status and popover content
├── Onboarding/
│ └── Welcome/ composed welcome flow and step views
├── Overlays/ SwiftUI overlay content
└── Settings/
├── Components/
│ ├── Controls/ settings editors, pickers, and previews
│ └── Structure/ pane scaffolds, rows, cards, and search results
├── ModelManagement/ model catalog and browser views
└── Panes/
├── About/ product and acknowledgement panes
└── Engine/ engine pane and backend-specific extensions
Files left directly inside a subsystem are intentionally its root owners or a small cohesive set.
For example, SuggestionEngineRouter.swift remains at Services/Runtime/ because it coordinates all
three backend folders, while FocusTracker.swift remains at Services/Focus/ because it owns the
whole focus lifecycle rather than one resolution or caching technique.
CotabbyTests/ mirrors the production responsibility after removing the leading Cotabby/. For
example:
Cotabby/Support/Suggestion/Output/SuggestionTextNormalizer.swift
CotabbyTests/Support/Suggestion/Output/SuggestionTextNormalizerTests.swift
Cotabby/Services/Runtime/Llama/LlamaSuggestionEngine.swift
CotabbyTests/Services/Runtime/Llama/LlamaSuggestionEngineStreamingTests.swift
Cotabby/App/Coordinators/Suggestion/SuggestionCoordinator.swift
CotabbyTests/App/Coordinators/Suggestion/SuggestionCoordinatorPredictionTests.swift
Tests that exercise several production values may stay at the nearest shared subsystem root. Evals
remain under CotabbyTests/Evals, and shared fixtures remain under CotabbyTests/TestSupport.
Support/Suggestion/Request/CaretWordContext.swiftdistinguishes a still-typed token from a delimiter-committed word.TypoGateand the correction replacement planner consume this value; pausing alone never makes correction eligible.Support/Suggestion/Output/CompletionSeamGuard.swiftreturns the same presentation decision for streamed and final output: wait for the first word, reject a malformed join, show a word ending, or show a phrase. A recognized completed word keeps its following phrase even from a one-letter prefix; unknown names and jargon can still show a conservative word ending.Support/Suggestion/Request/SuggestionRequestFactory.swiftapplies the optionalsuggestWithinWordspreference to new ordinary and speculative requests. The completion settings domain persists the choice, while active sessions remain free to follow matching typing.Services/Suggestion/State/SuggestionInteractionState.swiftholds a narrow range of typed characters awaiting Accessibility publication.SuggestionSessionReconcilertolerates only an older matching prefix during this handoff, so a typed space preserves the following words without treating unrelated edits as acceptance. Correction sessions never participate in type-through.Models/Suggestion/Session/ActiveSuggestionSession.swiftseparates the full prediction from the visible acceptance boundary. An uncertain word ending can retain following words without offering them early. TheshowFollowingWordscompletion preference uses the same boundary to show one word at a time; even full acceptance inserts only the current visible offer. Matching typing consumes the buffered prediction, while streaming may extend it without revising it.Support/Suggestion/Session/SuggestionContinuationPlan.swiftconstructs hypothetical completed or corrected text and its exact publication target. A virtual separating space asks for the next words rather than another ending; it never edits the host field. The coordinator's+Continuation.swiftowns one cancellable lookahead and attaches it to a terminal word ending, or holds it behind a correction until the editor publishes that correction. The live context buffer remains anchored to observed text throughout this work. Additional preaccept lookahead is limited to on-device engines; configured endpoints retain already-generated phrases but do not receive the new hypothetical-edit requests.Support/Spelling/WordPrefixIndex.swiftsupplies immutable exact-prefix candidates and bounded document/glossary vocabulary.SymSpellCorrectorbuilds its index on the existing background dictionary queue; fallback never uses spelling edit distance or changes typed letters.Support/Suggestion/Streaming/TypingCadence.swiftmeasures recent inter-letter intervals and controls presentation timing independently of generation debounce.SuggestionStreamingStatememoizes exact-word checks and closes the stream when a final result arrives.Support/Suggestion/Streaming/TypingPredictionCandidate.swifttracks matching typed characters against one on-device request and validates their exact Accessibility publication before rebasing the remaining text.SuggestionCoordinator+TypingPrediction.swiftowns that candidate and its expiry timer. The default-onpredictAheadWhileTypingsetting controls retention independently of streaming display; disabling it cancels retained work through the settings snapshot lifecycle.Support/Suggestion/Session/SuggestionDismissalMemory.swiftremembers explicit dismissal for at most 15 seconds in the same field and text context. It is bounded and never persisted.App/Coordinators/Suggestion/SuggestionCoordinator+WordCompletion.swiftadapts these pure values to the existing spell checker, dictionaries, settings, and cancellable presentation work.
Direct tests mirror those folders. SuggestionCoordinatorWordCompletionTests replays pauses after
individual letters, malformed streams, fallback acceptance, dismissal/cache behavior, and cancellation
against the actual coordinator with synthetic OS and engine boundaries. The phrase accuracy replay
uses the committed typo gate and final display policy, but deliberately excludes local fallback so
its score remains attributable to the model. Timing replay and coordinator interaction tests cover
presentation and acceptance separately; model-only scores do not represent the complete experience.
SuggestionCoordinatorContinuityTests covers buffered acceptance, hidden streaming growth, cached
word restoration, correction publication, and late cancellation. TypingExperienceEvalTests drives
the production coordinator with the real local engine and a synthetic editor, recording visible
and buffered text plus actual requests in build/eval/typing-experience.json. It does not measure
third-party editor AX behavior or visual placement.
- Identify its single dominant responsibility using the map above.
- Place or move its direct tests with it conceptually.
- Update tracked Markdown links and any scripts containing physical paths.
- Run
xcodegen generateand commit the regenerated project. - Run SwiftLint, a build, and
build-for-testingbefore opening a pull request.
When a file seems to fit several folders, that usually signals either a cross-subsystem contract
that belongs in Models, a root orchestrator that should remain above its collaborators, or a type
that owns too many responsibilities and should be split by behavior rather than hidden by nesting.
Support/Focus/FocusedInputPollingSignature.swiftdistinguishes navigation using live URL, title, placeholder and field geometry, while ignoring typing and volatile AX wrapper tokens. The focus resolver reads these facts before comparing sessions; surface metadata is not frozen in a cache.FocusedInputSessionIdentityinModels/Focus/FocusModels.swiftcarries that boundary through generation, acceptance and speculative work. Prediction memory has a session key separate from the geometry/style key so another conversation cannot restore an old suggestion.VisualContextCoordinatorrefreshes both backend profiles using their existing capture limits. Excerpts expire six seconds after capture starts, even while OCR is pending. Navigation clears the published excerpt immediately, and invalidation retires predictions conditioned on it.Support/Context/FocusedFieldScreenRegion.swiftkeeps the focused field out of that signal: its OCR lines never enter the excerpt and its pixels never miss the OCR cache, so typing is not mistaken for a changed screen while a different conversation still is.Support/Context/VisualContextExcerptStability.swiftdoes the same for OCR jitter on unchanged pixels: a near-identical refresh keeps the excerpt in use byte-identical.