fix: add oh-my-opencode-slim schema support (closes #2)#3
fix: add oh-my-opencode-slim schema support (closes #2)#3Poorgramer-Zack merged 3 commits intomainfrom
Conversation
- Add slim schema JSON file (converted from Zod schema) - Fix readBundledAsset path resolution (../../ instead of ../../../) - Add slim mode support to init command - Add slim preset validation to add command - Fix validator method (validate vs validatePreset) - Add bundled fallback for schema resolution Closes #2
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAdds a new oh-my-opencode-slim JSON Schema asset and extends init/add flows to handle "slim" mode with GitHub download, cache, and bundled-asset fallback, plus associated validator usage and expanded tests and mocks. Changes
Sequence DiagramsequenceDiagram
participant User
participant InitCmd as Init Command
participant SettingsMgr as SettingsManager
participant GitHub as GitHub API
participant BundledAssets as Bundled Assets
participant Cache as Local Cache
participant ConfigMgr as OmosConfigManager
User->>InitCmd: omo-switch init
InitCmd->>SettingsMgr: getEffectiveType()
SettingsMgr-->>InitCmd: "slim"
rect rgba(100, 200, 100, 0.5)
Note over InitCmd: Slim mode schema retrieval
InitCmd->>Cache: check cached slim schema
alt Cached
Cache-->>InitCmd: schema
else Not cached
InitCmd->>GitHub: download slim schema
alt Download succeeds
GitHub-->>InitCmd: schema
InitCmd->>Cache: save schema
else Download fails
InitCmd->>BundledAssets: read bundled slim schema
BundledAssets-->>InitCmd: schema
InitCmd->>Cache: save schema
end
end
end
InitCmd->>ConfigMgr: new OmosConfigManager("user")
InitCmd->>ConfigMgr: configExists()
alt Exists
ConfigMgr-->>InitCmd: true
InitCmd->>User: log existing config path
else Not exists
ConfigMgr-->>InitCmd: false
InitCmd->>BundledAssets: load default-template-slim.json
BundledAssets-->>InitCmd: template
InitCmd->>ConfigMgr: saveConfig(template)
ConfigMgr-->>User: config created at path
end
InitCmd-->>User: initialization complete
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Docstrings generation was requested by @Poorgramer-Zack. * #3 (comment) The following files were modified: * `src/commands/add.ts` * `src/utils/downloader.ts`
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/commands/add.test.ts (1)
230-235:⚠️ Potential issue | 🟠 MajorDefault slim test setup doesn’t provide the slim schema fallback asset.
Slim tests fail early with “Slim schema not found in cache...” before reaching the actual preset assertions.
Proposed baseline mock alignment
vi.mocked(readBundledAsset).mockImplementation((name: string) => { if (name === "oh-my-opencode.schema.json") { return '{"$schema":"test"}'; } + if (name === "oh-my-opencode-slim.schema.json") { + return '{"$schema":"test-slim"}'; + } return null; });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/commands/add.test.ts` around lines 230 - 235, The test's mocked readBundledAsset (vi.mocked(readBundledAsset)) doesn't return the slim schema fallback, causing tests to error out early; update the mockImplementation in src/commands/add.test.ts so that when readBundledAsset is called with the slim fallback asset name used by the code (the filename your runtime tries to load for the slim schema) it returns a valid slim schema JSON string (e.g., '{"$schema":"slim"}') while preserving the existing "oh-my-opencode.schema.json" branch, ensuring the slim fallback is available for the preset assertions to run.
🧹 Nitpick comments (1)
src/commands/init.ts (1)
28-58: Extract shared schema fetch/fallback logic to one helper.The OMO and slim branches duplicate almost identical download→cache→bundled fallback flow.
Refactor sketch
+async function ensureSchema( + store: StoreManager, + spinner: ReturnType<typeof ora>, + schemaUrl: string, + schemaFile: string, + bundledFile: string, + label: string +): Promise<void> { + const cachePath = path.join(store.getCacheSchemaPath(), schemaFile); + try { + await downloadFile(schemaUrl, store.getCacheSchemaPath(), schemaFile, { source: "github" }); + spinner.succeed(`${label} downloaded from GitHub`); + } catch (err) { + if (fs.existsSync(cachePath)) { + spinner.warn(`Failed to download ${label.toLowerCase()}: ${err instanceof Error ? err.message : "Unknown error"}`); + spinner.succeed(`Using cached ${label.toLowerCase()}`); + return; + } + const bundled = readBundledAsset(bundledFile); + if (!bundled) throw new Error(`Failed to download or find bundled ${label.toLowerCase()}`); + store.saveCacheFile(store.getCacheSchemaPath(), schemaFile, bundled, { source: "bundled" }); + spinner.succeed(`Using bundled ${label.toLowerCase()}`); + } +}Also applies to: 61-90
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/commands/init.ts` around lines 28 - 58, The schema download/caching/fallback flow in init (around downloadFile, schemaCachePath, readBundledAsset, store.saveCacheFile, and spinner usage) is duplicated; extract that logic into a single helper (e.g., fetchSchemaOrFallback) that attempts downloadFile(SCHEMA_URL,...), checks fs.existsSync(schemaCachePath) for cache, falls back to readBundledAsset and store.saveCacheFile when needed, and returns the resolved schema path or throws; replace both duplicated blocks with calls to this helper and propagate spinner updates and thrown errors from the helper back to the caller.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/commands/add.test.ts`:
- Around line 519-543: The test still asserts that downloadFile was called for
the slim schema even though add.ts now uses a bundled asset fallback; update the
test around runAdd so it no longer expects downloadFile to be invoked for
"oh-my-opencode-slim.schema.json" (remove or replace those
expect(downloadFile)... assertions) and instead assert the bundled fallback
behavior — e.g., expect(downloadFile).not.toHaveBeenCalled() and/or assert that
fs.readFileSync (or the code path that reads bundled assets) was called with the
bundled slim schema filename or that runAdd completed by invoking
OmosConfigManager.addPreset/getPreset as appropriate; update the same pattern
for the similar assertions in the 545-575 block as well.
- Around line 59-67: The test mock for OmosValidator exposes validatePreset but
the command under test calls validator.validate; update the mock in the test to
match the real API by adding a validate method (or alias validate to the
existing mockValidatePreset) on the mocked OmosValidator class so that calls to
validator.validate(...) succeed; reference the OmosValidator class and the mock
function __mockValidatePreset/ mockValidatePreset to keep behavior identical to
current tests.
---
Outside diff comments:
In `@src/commands/add.test.ts`:
- Around line 230-235: The test's mocked readBundledAsset
(vi.mocked(readBundledAsset)) doesn't return the slim schema fallback, causing
tests to error out early; update the mockImplementation in
src/commands/add.test.ts so that when readBundledAsset is called with the slim
fallback asset name used by the code (the filename your runtime tries to load
for the slim schema) it returns a valid slim schema JSON string (e.g.,
'{"$schema":"slim"}') while preserving the existing "oh-my-opencode.schema.json"
branch, ensuring the slim fallback is available for the preset assertions to
run.
---
Nitpick comments:
In `@src/commands/init.ts`:
- Around line 28-58: The schema download/caching/fallback flow in init (around
downloadFile, schemaCachePath, readBundledAsset, store.saveCacheFile, and
spinner usage) is duplicated; extract that logic into a single helper (e.g.,
fetchSchemaOrFallback) that attempts downloadFile(SCHEMA_URL,...), checks
fs.existsSync(schemaCachePath) for cache, falls back to readBundledAsset and
store.saveCacheFile when needed, and returns the resolved schema path or throws;
replace both duplicated blocks with calls to this helper and propagate spinner
updates and thrown errors from the helper back to the caller.
ℹ️ Review info
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
shared/assets/oh-my-opencode-slim.schema.jsonsrc/commands/add.test.tssrc/commands/add.tssrc/commands/init.test.tssrc/commands/init.tssrc/utils/downloader.ts
- Rename validatePreset to validate in OmosValidator mock (matches add.ts usage) - Fix error message assertion to match actual 'Slim schema not found' string - Add schema cache mock for 'exits when preset exists without --force' test
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/commands/add.test.ts (1)
522-536: Strengthen cache-miss slim test to assert bundled fallback was attempted.Right now this test only checks failure output. Add an assertion that
readBundledAsset("oh-my-opencode-slim.schema.json")was called so the test verifies fallback flow, not just failure text.Proposed test hardening
-it("fails when slim schema not in cache", async () => { +it("fails when slim schema is missing in both cache and bundled assets", async () => { const storeModule = await import("../store"); vi.spyOn(storeModule.SettingsManager.prototype, "getEffectiveType").mockReturnValue("slim"); + vi.mocked(readBundledAsset).mockReturnValue(null); vi.mocked(fs.existsSync).mockImplementation((p: any) => { const s = path.normalize(String(p || "")); const base = path.basename(s).toLowerCase(); if (base === "preset.json") return true; return false; }); vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ orchestrator: { model: "test/model" } })); await runAdd("/path/to/preset.json", { scope: "user" }); + expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json"); expect(mockSpinner.fail).toHaveBeenCalledWith(expect.stringContaining("schema not found in cache")); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/commands/add.test.ts` around lines 522 - 536, The test "fails when slim schema not in cache" currently only asserts failure text; add an assertion that the bundled-fallback loader was attempted by spying/mocking readBundledAsset and expecting it was called for the slim schema (e.g. expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json") ) after calling runAdd; ensure you set up the spy/mock on readBundledAsset before invoking runAdd and restore any mocks if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@src/commands/add.test.ts`:
- Around line 522-536: The test "fails when slim schema not in cache" currently
only asserts failure text; add an assertion that the bundled-fallback loader was
attempted by spying/mocking readBundledAsset and expecting it was called for the
slim schema (e.g.
expect(readBundledAsset).toHaveBeenCalledWith("oh-my-opencode-slim.schema.json")
) after calling runAdd; ensure you set up the spy/mock on readBundledAsset
before invoking runAdd and restore any mocks if needed.
- Add readBundledAsset slim schema fallback in test mock - Extract ensureSchema helper to reduce duplication in init.ts - Override readBundledAsset in 'fails when slim schema not in cache' test - Remove unused STORE_VERSION import
Summary
Closes #2
Summary by CodeRabbit
New Features
Tests