* Nate/control plane client (#1691)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* 🚑 fix constant warnings when onboarding with Ollama

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* team analytics

* apply control plane settings

* workos auth

* ide protocol get session info

* UI for auth

* profile switching

* small fixes

* updates

* refresh tokens

* updates

* fix tsc errs

* model select in toolbar to make room for profile selector

* prod client id

* link to prod URL

* internal beta option

* profiles change listener

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* temporary patch for type errs

* Dev (#1689)

* Fix an issue where CMD+K does not clear the terminal when the terminal has focus (#1671)

On MacOS, ⌘+K is bound, by default, to Terminal:Clear. Without this
change ⌘+K does not clear the terminal but instead iniates a chord
sequence and waits for the next stroke of the chord.

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* Change treeSitter to cache the Language objects it loads from wasm (#1672)

Without this change, for a repository with 600 typescript files, the
indexer would fail to finish correctly and there would be many of the
following errors in the webview console log:

'Unable to load language for file ${path} RuntimeError: table index is out of bounds'

The following bash will create a repo that reproduces the problem:

current_path="."

for ((i=1; i<=20; i++)); do
    new_folder="folder-$i"
    mkdir -p "$current_path/$new_folder"
    current_path="$current_path/$new_folder"

    for ((a=1; a<=30; a++)); do
      head -c 10000 /dev/urandom | base64 > "$current_path/file-$a.ts"
    done
done

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* acknowledge sourcemap flag in esbuild.js

* don't run jetbrains-release.yaml on vscode releases

* further testing for walkDir

* chore: add telemetry to commands (#1673)

* test: Add basic unit test to baseLLM (#1668)

* update version

* test: Add basic unit test to baseLLM

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: inimaz <imaz@ai-verse.com>

* feat: add Quick Actions CodeLens feature (#1674)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* add voyage rerank-1

* import Handlebars

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* small UI tweaks

* media query

* feat: add best experience onboarding

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* chore: add telemetry for full screen toggle (#1618)

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* manually implement stop tokens for hf inference api

* chore: onboarding metrics (#1626)

* fix: pageview tracking

* feat: add onboarding telemetry

* create single `onboardingStatus` type

* improved var naming

* remove console logs

* fix windows performance issue

* rename vscodeExtension.ts

* migration of onboarding variables

* "stash" instead of "delete" in indexing progress

* fix preview.yaml

* also fix main.yaml

* Update troubleshooting.md (#1637)

* feat: add quick actions

* Update index.d.ts

* quick actions mvp

* update docs

* subscribe to vscode change settings

* Update commands.ts

* cleanup

* Update quick-actions.md

* Update VerticalPerLineCodeLensProvider.ts

* resolve feedback

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>

* chore: add `isCommandEvent` to command telemetry (#1675)

* chore: add `isCommandEvent` to command telemetry

* Update commands.ts

* Nate/better retrieval (#1677)

* deduplicatearray tests

* break out separate retrieval pipelines

* IConfigHandler

* tests for codebase indexer

* better .continueignore for continue

* indexing fixes

* ignore .gitignore and .continueignore when indexing

* retrieval pipeline improvements

* fix formatting err in out .continueignore

* add necessary filter to lance_db_cache

* update package.json version

* skip unused tests

* don't ignore .prompt files

* update version

* Update pull_request_template.md

* don't use multi-media format when there are multiple text items

* add free trial experience (#1685)

* fix: add code range for quick actions/fixes (#1687)

* fix: add code range for quick actions/fixes

* Update test.js

* add pathSep message type

* docs improvements

* jetbrains fix

* update package.json version

---------

Co-authored-by: Rob Leidle <rleidle@gmail.com>
Co-authored-by: Rob Leidle <rleidle@tesla.com>
Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: inimaz <imaz@ai-verse.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>

* update package.json version

* skip extension tests

* update package.json version

* handlebars import

* don't push package.json version change from CI

* fix: scroll issues w/ code blocks (#1688)

* fix: scroll issues w/ code blocks

* chore: name offset

* chore: remove docs start

* chore: update headings on troubleshooting.md (#1696)

* ignore .svn folder for indexing (#1699)

* chore: clearer naming for `useSuffix` (#1702)

* chore: clearer naming for `useSuffix`

* schema updates

* fix: cmd+shft+l closes sidebar if focused (#1638)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* add voyage rerank-1

* import Handlebars

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* small UI tweaks

* media query

* feat: add best experience onboarding

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* chore: add telemetry for full screen toggle (#1618)

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* manually implement stop tokens for hf inference api

* chore: onboarding metrics (#1626)

* fix: pageview tracking

* feat: add onboarding telemetry

* create single `onboardingStatus` type

* improved var naming

* remove console logs

* fix windows performance issue

* rename vscodeExtension.ts

* migration of onboarding variables

* "stash" instead of "delete" in indexing progress

* fix preview.yaml

* also fix main.yaml

* Update troubleshooting.md (#1637)

* feat: close panel if main input is focused

* add skip param

* Update TipTapEditor.tsx

* merge dev

* Update commands.ts

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>

* bugfix: quick actions undefined array (#1704)

* feat: add rich quick pick for quick edit (#1706)

* feat: multistep quick pick

* fix: multi step for context provider

* Update test.js

* Create deepseek.md (#1708)

* style: add max height to model selector (#1712)

* update styling

* remove testing code

* remove comments

* feat: add tutorial card (#1716)

* feat: create tutorial card

* Update TutorialCard.tsx

* feat: add file search to quick edit (#1714)

* feat: multistep quick pick

* fix: multi step for context provider

* Update test.js

* add file search

* complete file search

* remove unused import

* add comments

* Update utils.ts

* update naming

* chore: move quick pick instantiation (#1723)

* Break out into NPM modules (#1726)

* config.json types

* export all schemas

* break out request logic into packages

* update openai adapters to export body types

* update packaging of npm modules

* update packages

* continue proxy

* mistral

* Fix typo in documentation (#1722)

In  set-up-codestral.md
"Trobleshooting" -> "Troubleshooting"

* update package.json version

* 🪄 model dropdown, control plane (#1692)

* Nate/control plane client (#1691)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* 🚑 fix constant warnings when onboarding with Ollama

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* team analytics

* apply control plane settings

* workos auth

* ide protocol get session info

* UI for auth

* profile switching

* small fixes

* updates

* refresh tokens

* updates

* fix tsc errs

* model select in toolbar to make room for profile selector

* prod client id

* link to prod URL

* internal beta option

* profiles change listener

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* temporary patch for type errs

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* skip extension tests

* JetBrains status bar spinner for autocomplete

* Remove unused images

* partial accept jetbrains

* fix double-rendering of jetbrains completions

* fix offset of multi-line jetbrains completions

* enable/disable actions

* upgrade to version 0.0.54

* fix: wrap editor buttons when out of space (#1727)

* Add .continuerc file to config directory on activation to prevent it's indexing. (#1733)

* Updated the content links that were deprecated in the document (#1709)

Co-authored-by: Ihe Fan <ih.fan.1027@gmail.com>

* Nate/dev (#1739)

* JetBrains status bar spinner for autocomplete

* Remove unused images

* partial accept jetbrains

* fix double-rendering of jetbrains completions

* fix offset of multi-line jetbrains completions

* enable/disable actions

* upgrade to version 0.0.54

* llm-info package

* small profile switching improvements

* instruct cmd+I not to leave placeholders

* @ files in context-providers docs

* onboarding fix

* update jetbrains ci to build gui

* feat: single default quick pick to edit (#1743)

* feat: single default quick pick to edit

* Update quick-actions.md

* Update quick-actions.md

* use defaultQuickAction

* quick fixes

* fix: handle line removal diff (#1744)

* fix: handle line removal diff

* remove comments

* Configurable `maxChunkSize` for embedding providers (#1746)

* Add `maxChunkSize` to `EmbeddingsProvider`

* Add `maxChunkSize` to schema

* add support for docs via config (#1594)

* mistral mamba (#1748)

* 🐍 mistral mamba

* autoscale retrieval based on context length

* autoscale retrieval based on context length

* fix input box movement

* update jetbrains build

* test: add myers diff tests (#1754)

* feat: enhance help center (#1755)

* feat: enhance help center

* Update help.tsx

* feat: add azure provider config (#1764)

* autocomplete reload fix

* logout of control plane

* Update QuickEditQuickPick.ts (#1772)

* Update QuickEditQuickPick.ts

* updates

* Update QuickEditQuickPick.ts

* pass refreshed access token to continue-proxy model

* test: add dir read check for walkDir (#1773)

* test: add dir read check for walkDir

* Update ignore.ts

* Update walkDir.test.ts

* Update walkDir.test.ts

* gpt-4o-mini

* gpt-4o-mini

* gpt4omini to ui selector

* fix: layout alignment (#1779)

* fix: delete old docs index on force re-index (#1778)

* add "Codebase Force Re-Index" command (#1757)

* Add `HuggingFaceTEIReranker` (#1711)

* Add `HuggingFaceTEIReranker`

* Add `huggingface-tei` to `config_schema.json`

* update package.json version

* update config schemas

* skip test failing only due to type error

* fix: convert `walkDir` to an async generator (#1783)

* walkdir to async generator

* add yields

* handle ignore files

* Update CodebaseIndexer.ts

* Update walkDir.ts

* chore: bump VS Code ext version

* fix completions support in ContinueProxy

* add test for walkDir

* IAnalyticsProvider

* feat: crawl `.mdx` docs

* update workspaces on session info change

* rename from profile to workspace (user-facing)

* update config schema files

* feat: improve chat thread ui for better readability (#1786)

* add "language" template variable for autocomplete

* Enable debug logs (#1800)

* Add an enableDebugLogs flag

* Send logs to VSCode

* Refresh index fixes (#1795)

* Use the resultType given to markComplete

This fixes an issue where if there were multiple result types in itemToAction such as an update with UpdateNewVersion and UpdateOldVersion, only the UpdateOldVersion would be hit (which is a noop) and the UpdateNewVersion would never be fired, causing us to never update the timestamp of the tag_catalog.

* Add a Compute and UpdateLastUpdated to refreshIndex

Removes the ability to insert duplicate rows if we're just computing the result. Instead we replace the existing row instead.

* Don't insert compute tags

They are REPLACEd in markComplete now.

* docs: change page heading to model providers (#1684)

* feat: allow JetBrains users to index docs (#1797)

* feat: allow JetBrains users to index docs

* update docs service

* update global context

* throw error popup on jetbrains + transformers

* update toast notifications

* update typings

* fix tsc errors

* Index on file change (#1785)

* Reload the submenu items when the context provider data is refreshed

* update version

* Just call refreshSubmenuItems

* remove log statements

* cleanup

* Remove the Promise declaration

* Copy currentFiles to a new dict since we're going to mutate it

Don't mutate the caller's currentFiles unexpectedly

* Remove reIndexFile and just call index/forceReIndex

* We MUST await the refreshCodebaseIndex call

* Expose send on core

* remove unused import

* Reindex the workspaces on save

* Call core.send

Ideally, we can implement externalRequest on the webview later so we don't have to expose messenger to the VSCode extension

* Always refreshSubmenuItems in refreshCodebaseIndex

* whitespace

* Change messenger back to private

* Add Pause Codebase On Start setting (#1788)

* Add a skipInitialSync function

* Add pauseInitialCodebaseIndex

* docs

* version bump

* Rename to pauseCodebaseIndexOnStart

* Un-shadow file context provider (#1801)

* allow FileContextProvider to handle files

* remove commented-out lines

* chore: add telemetry to alt-enter (#1805)

* Set the indexProgress indicator to paused on startup if pauseCodebaseIndexOnStart is set (#1804)

* Fix Input Toolbar layout (#1792)

* set to flex flex-column

* Remove fixed height and always show the StyledDivs content to hold its size

* Add a Delete Message button to the StepContainer (#1790)

* Add a delete button

* add a delete message action to the GUI

* Fix off by one error

* format

* This index should be less than length

* Update to trash icon

* Simplify walkDir(...) and improve performance by roughly 10x in larger repos (#1806)

The performance of WalkDir is improved by replacing the recursive DFS
with a stack based implementation (less memory in-use during peak
exploration). In addition, some unnecessary flags and options were
removed which allowed the code to be overall simplified. Much less rule
matching is occuring with the same files returned.

Some performance results on my linux host:

small repo:
- 649 files returned by walkDir()
- 9 .gitignore files
- walkDir() old vs new duration: 918 ms to 143 ms

medium sized repo:
- 9271 returned by walkDir()
- 35 .gitignore files
- walkDir() old vs new duration: 10,886 ms to 970ms

large sized repo:
- 197,900 files returned by walkDir()
- 929 .gitignore files
- walkDir() old vs new duration: 498,151 ms to 37,353 ms

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* modified assistant indicator in UI

* update package.json version

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
Co-authored-by: Rob Leidle <rleidle@gmail.com>
Co-authored-by: Rob Leidle <rleidle@tesla.com>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: inimaz <imaz@ai-verse.com>
Co-authored-by: Anaël Bonnafous <71386173+AnaelBonnafous@users.noreply.github.com>
Co-authored-by: Huy Tran <119860259+tranquochuy645@users.noreply.github.com>
Co-authored-by: Gabriel Gordbegli <ggordbegli@gmail.com>
Co-authored-by: Raven-1027 <83693755+Raven-1027@users.noreply.github.com>
Co-authored-by: Ihe Fan <ih.fan.1027@gmail.com>
Co-authored-by: Lukas Kreussel <65088241+LLukas22@users.noreply.github.com>
Co-authored-by: Josh Vera <josh@joshvera.com>
Co-authored-by: Peter Zaback <pzaback@gmail.com>
This commit is contained in:
Nate Sesti 2024-07-22 22:15:27 -07:00 • committed by GitHub
parent e58fddc6d4
commit 82db97e66d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 1651 additions and 3150 deletions

View file

@ -109,6 +109,7 @@
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"ts-jest": "^29.1.1"

View file

@ -581,6 +581,7 @@ export class CompletionProvider {
suffix,
filename,
reponame,
language: lang.name,
});
} else {
// Let the template function format snippets

View file

@ -1,6 +1,7 @@
import type { LineFilter } from "./lineStream";
export interface AutocompleteLanguageInfo {
name: string;
topLevelKeywords: string[];
singleLineComment: string;
endOfLine: string[];
@ -14,6 +15,7 @@ export interface AutocompleteLanguageInfo {
// TypeScript
export const Typescript = {
name: "TypeScript",
topLevelKeywords: ["function", "class", "module", "export", "import"],
singleLineComment: "//",
endOfLine: [";"],
@ -21,6 +23,7 @@ export const Typescript = {
// Python
export const Python = {
name: "Python",
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
// This stops the model from trying to complete the start of a new markdown block
topLevelKeywords: ["def", "class", '"""#'],
@ -30,6 +33,7 @@ export const Python = {
// Java
export const Java = {
name: "Java",
topLevelKeywords: ["class", "function"],
singleLineComment: "//",
endOfLine: [";"],
@ -37,6 +41,7 @@ export const Java = {
// C++
export const Cpp = {
name: "C++",
topLevelKeywords: ["class", "namespace", "template"],
singleLineComment: "//",
endOfLine: [";"],
@ -44,6 +49,7 @@ export const Cpp = {
// C#
export const CSharp = {
name: "C#",
topLevelKeywords: ["class", "namespace", "void"],
singleLineComment: "//",
endOfLine: [";"],
@ -51,6 +57,7 @@ export const CSharp = {
// C
export const C = {
name: "C",
topLevelKeywords: ["if", "else", "while", "for", "switch", "case"],
singleLineComment: "//",
endOfLine: [";"],
@ -58,6 +65,7 @@ export const C = {
// Scala
export const Scala = {
name: "Scala",
topLevelKeywords: ["def", "val", "var", "class", "object", "trait"],
singleLineComment: "//",
endOfLine: [";"],
@ -65,6 +73,7 @@ export const Scala = {
// Go
export const Go = {
name: "Go",
topLevelKeywords: ["func", "package", "import", "type"],
singleLineComment: "//",
endOfLine: [],
@ -72,6 +81,7 @@ export const Go = {
// Rust
export const Rust = {
name: "Rust",
topLevelKeywords: ["fn", "mod", "pub", "struct", "enum", "trait"],
singleLineComment: "//",
endOfLine: [";"],
@ -79,6 +89,7 @@ export const Rust = {
// Haskell
export const Haskell = {
name: "Haskell",
topLevelKeywords: [
"data",
"type",
@ -95,6 +106,7 @@ export const Haskell = {
// PHP
export const PHP = {
name: "PHP",
topLevelKeywords: ["function", "class", "namespace", "use"],
singleLineComment: "//",
endOfLine: [";"],
@ -102,6 +114,7 @@ export const PHP = {
// Ruby on Rails
export const RubyOnRails = {
name: "Ruby on Rails",
topLevelKeywords: ["def", "class", "module"],
singleLineComment: "#",
endOfLine: [],
@ -109,6 +122,7 @@ export const RubyOnRails = {
// Swift
export const Swift = {
name: "Swift",
topLevelKeywords: ["func", "class", "struct", "import"],
singleLineComment: "//",
endOfLine: [";"],
@ -116,6 +130,7 @@ export const Swift = {
// Kotlin
export const Kotlin = {
name: "Kotlin",
topLevelKeywords: ["fun", "class", "package", "import"],
singleLineComment: "//",
endOfLine: [";"],
@ -123,6 +138,7 @@ export const Kotlin = {
// Ruby
export const Ruby = {
name: "Ruby",
topLevelKeywords: ["class", "module", "def"],
singleLineComment: "#",
endOfLine: [],
@ -130,6 +146,7 @@ export const Ruby = {
// Clojure
export const Clojure = {
name: "Clojure",
topLevelKeywords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
singleLineComment: ";",
endOfLine: [],
@ -137,6 +154,7 @@ export const Clojure = {
// Julia
export const Julia = {
name: "Julia",
topLevelKeywords: [
"function",
"macro",
@ -155,6 +173,7 @@ export const Julia = {
// F#
export const FSharp = {
name: "F#",
topLevelKeywords: [
"let",
"type",
@ -173,6 +192,7 @@ export const FSharp = {
// R
export const R = {
name: "R",
topLevelKeywords: [
"function",
"if",
@ -189,6 +209,7 @@ export const R = {
// Dart
export const Dart = {
name: "Dart",
topLevelKeywords: ["class", "import", "void", "enum"],
singleLineComment: "//",
endOfLine: [";"],
@ -196,6 +217,7 @@ export const Dart = {
// Solidity
export const Solidity = {
name: "Solidity",
topLevelKeywords: [
"contract",
"event",
@ -218,6 +240,7 @@ export const Solidity = {
// YAML
export const YAML: AutocompleteLanguageInfo = {
name: "YAML",
topLevelKeywords: [],
singleLineComment: "#",
endOfLine: [],
@ -258,6 +281,7 @@ export const YAML: AutocompleteLanguageInfo = {
};
export const Markdown: AutocompleteLanguageInfo = {
name: "Markdown",
topLevelKeywords: [],
singleLineComment: "",
endOfLine: [],

View file

@ -1,4 +1,7 @@
import { ControlPlaneClient } from "../control-plane/client.js";
import {
ControlPlaneClient,
ControlPlaneSessionInfo,
} from "../control-plane/client.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -118,44 +121,20 @@ export class ConfigHandler {
return this.profiles.filter((p) => p.profileId !== this.selectedProfileId);
}
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private readonly controlPlaneClient: ControlPlaneClient,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
writeLog,
);
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
this.selectedProfileId = localProfileLoader.profileId;
// Always load local profile immediately in case control plane doesn't load
try {
this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
}
// Load control plane profiles
// TODO
private async fetchControlPlaneProfiles() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient.listWorkspaces().then(async (workspaces) => {
this.profiles = this.profiles.filter(
(profile) => profile.profileId === "local",
);
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
ide,
ideSettingsPromise,
writeLog,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles.push(new ProfileLifecycleManager(profileLoader));
@ -184,6 +163,36 @@ export class ConfigHandler {
});
}
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private controlPlaneClient: ControlPlaneClient,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
writeLog,
);
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
this.selectedProfileId = localProfileLoader.profileId;
// Always load local profile immediately in case control plane doesn't load
try {
this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
}
// Load control plane profiles
this.fetchControlPlaneProfiles();
}
async setSelectedProfile(profileId: string) {
this.selectedProfileId = profileId;
const newConfig = await this.loadConfig();
@ -209,6 +218,15 @@ export class ConfigHandler {
this.reloadConfig();
}
updateControlPlaneSessionInfo(
sessionInfo: ControlPlaneSessionInfo | undefined,
) {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
);
this.fetchControlPlaneProfiles();
}
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (profiles: ProfileDescription[]) => void,

View file

@ -6,6 +6,7 @@ import type {
IContextProvider,
LoadSubmenuItemsArgs,
} from "../index.js";
export abstract class BaseContextProvider implements IContextProvider {
options: { [key: string]: any };

View file

@ -1,15 +1,16 @@
import fetch from "node-fetch";
import {
Chunk,
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
EmbeddingsProvider,
LoadSubmenuItemsArgs,
SiteIndexingConfig,
Reranker,
} from "../../index.js";
import { DocsService } from "../../indexing/docs/DocsService.js";
import configs from "../../indexing/docs/preIndexedDocs.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js";
import { Telemetry } from "../../util/posthog.js";
import { BaseContextProvider } from "../index.js";
class DocsContextProvider extends BaseContextProvider {
@ -21,6 +22,7 @@ class DocsContextProvider extends BaseContextProvider {
description: "Type to search docs",
type: "submenu",
};
private docsService: DocsService;
constructor(options: any) {
@ -28,34 +30,96 @@ class DocsContextProvider extends BaseContextProvider {
this.docsService = DocsService.getInstance();
}
private async _getIconDataUrl(url: string): Promise<string | undefined> {
private async _rerankChunks(
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
) {
let chunksCopy = [...chunks];
try {
const response = await fetch(url);
if (!response.headers.get("content-type")?.startsWith("image/")) {
console.log("Not an image: ", await response.text());
return undefined;
}
const buffer = await response.buffer();
const base64data = buffer.toString("base64");
return `data:${response.headers.get("content-type")};base64,${base64data}`;
const scores = await reranker.rerank(fullInput, chunksCopy);
chunksCopy.sort(
(a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
chunksCopy = chunksCopy.splice(
0,
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
);
} catch (e) {
console.log("E: ", e);
return undefined;
console.warn(`Failed to rerank docs results: ${e}`);
chunksCopy = chunksCopy.splice(
0,
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
);
}
return chunksCopy;
}
private _sortByPreIndexedDocs(
submenuItems: ContextSubmenuItem[],
): ContextSubmenuItem[] {
// Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized
return submenuItems.sort((a, b) => {
const aTitleInConfigs = a.metadata?.preIndexed ?? false;
const bTitleInConfigs = b.metadata?.preIndexed ?? false;
// Primary criterion: Items not in configs come first
if (!aTitleInConfigs && bTitleInConfigs) {
return -1;
} else if (aTitleInConfigs && !bTitleInConfigs) {
return 1;
} else {
// Secondary criterion: Alphabetical order when both items are in the same category
return a.title.toString().localeCompare(b.title.toString());
}
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Not supported in JetBrains IDEs right now
if ((await extras.ide.getIdeInfo()).ideType === "jetbrains") {
throw new Error(
"The @docs context provider is not currently supported in JetBrains IDEs. We'll have an update soon!",
const ideInfo = await extras.ide.getIdeInfo();
const isJetBrains = ideInfo.ideType === "jetbrains";
const isJetBrainsAndPreIndexedDocsProvider =
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
ideInfo,
extras.embeddingsProvider.id,
);
if (isJetBrainsAndPreIndexedDocsProvider) {
extras.ide.errorPopup(
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const preIndexedDoc = preIndexedDocs[query];
let embeddingsProvider: EmbeddingsProvider;
if (!!preIndexedDoc && !isJetBrains) {
// Pre-indexed docs should be filtered out in `loadSubmenuItems`,
// for JetBrains users, but we sanity check that here
Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
embeddingsProvider = DocsService.preIndexedDocsEmbeddingsProvider;
} else {
embeddingsProvider = extras.embeddingsProvider;
}
const embeddingsProvider = new TransformersJsEmbeddingsProvider();
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
let chunks = await this.docsService.retrieve(
@ -66,22 +130,11 @@ class DocsContextProvider extends BaseContextProvider {
);
if (extras.reranker) {
try {
const scores = await extras.reranker.rerank(extras.fullInput, chunks);
chunks.sort(
(a, b) => scores[chunks.indexOf(b)] - scores[chunks.indexOf(a)],
);
chunks = chunks.splice(
0,
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
);
} catch (e) {
console.warn(`Failed to rerank docs results: ${e}`);
chunks = chunks.splice(
0,
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
);
}
chunks = await this._rerankChunks(
chunks,
extras.reranker,
extras.fullInput,
);
}
return [
@ -96,7 +149,7 @@ class DocsContextProvider extends BaseContextProvider {
.slice(1)
.join("/")
: chunk.otherMetadata?.title || chunk.filepath,
description: chunk.filepath, // new URL(chunk.filepath, query).toString(),
description: chunk.filepath,
content: chunk.content,
}))
.reverse(),
@ -109,64 +162,51 @@ class DocsContextProvider extends BaseContextProvider {
];
}
// Get combined site configs from preIndexedDocs and options.sites.
private _getDocsSitesConfig(): SiteIndexingConfig[] {
return [...configs, ...(this.options?.sites || [])];
}
// Get indexed docs as ContextSubmenuItems from database.
private async _getIndexedDocsContextSubmenuItems(): Promise<ContextSubmenuItem[]> {
return (await this.docsService.list()).map((doc) => ({
title: doc.title,
description: new URL(doc.baseUrl).hostname,
id: doc.baseUrl,
}));
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const ideInfo = await args.ide.getIdeInfo();
const isJetBrains = ideInfo.ideType === "jetbrains";
const configSites = this.options?.sites || [];
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
for (const item of await this._getIndexedDocsContextSubmenuItems()) {
submenuItemsMap.set(item.id, item);
if (!isJetBrains) {
// Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
// However, we don't ship transformers.js with the JetBrains extension.
// So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
metadata: {
preIndexed: true,
},
});
}
}
for (const config of this._getDocsSitesConfig()) {
submenuItemsMap.set(config.startUrl, {
id: config.startUrl,
title: config.title,
description: new URL(config.startUrl).hostname,
metadata: { preIndexed: !!configs.find((cnf) => cnf.title === config.title), },
for (const { title, baseUrl } of await this.docsService.list()) {
submenuItemsMap.set(baseUrl, {
title,
id: baseUrl,
description: new URL(baseUrl).hostname,
});
}
for (const { startUrl, title } of configSites) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
});
}
const submenuItems = Array.from(submenuItemsMap.values());
// Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized
submenuItems.sort((a, b) => {
const aTitleInConfigs = a.metadata?.preIndexed ?? false;
const bTitleInConfigs = b.metadata?.preIndexed ?? false;
// Primary criterion: Items not in configs come first
if (!aTitleInConfigs && bTitleInConfigs) {
return -1;
} else if (aTitleInConfigs && !bTitleInConfigs) {
return 1;
} else {
// Secondary criterion: Alphabetical order when both items are in the same category
return a.title.toString().localeCompare(b.title.toString());
}
});
// const icons = await Promise.all(
// submenuItems.map(async (item) =>
// item.iconUrl ? this._getIconDataUrl(item.iconUrl) : undefined,
// ),
// );
// icons.forEach((icon, i) => {
// submenuItems[i].iconUrl = icon;
// });
if (!isJetBrains) {
return this._sortByPreIndexedDocs(submenuItems);
}
return submenuItems;
}

View file

@ -56,11 +56,5 @@ const Providers: (typeof BaseContextProvider)[] = [
export function contextProviderClassFromName(
name: ContextProviderName,
): typeof BaseContextProvider | undefined {
const cls = Providers.find((cls) => cls.description.title === name);
if (!cls) {
return undefined;
}
return cls;
return Providers.find((cls) => cls.description.title === name);
}

View file

@ -1,28 +1,34 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider";
function createAnalyticsProvider(
config: Analytics,
): IAnalyticsProvider | undefined {
// @ts-ignore
switch (config.provider) {
case "posthog":
return new PostHogAnalyticsProvider();
default:
return undefined;
}
}
export class TeamAnalytics {
static client: any = undefined;
static provider: IAnalyticsProvider | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static extensionVersion: string | undefined = undefined;
static async capture(event: string, properties: { [key: string]: any }) {
TeamAnalytics.client?.capture({
distinctId: TeamAnalytics.uniqueId,
event,
properties: {
...properties,
os: TeamAnalytics.os,
extensionVersion: TeamAnalytics.extensionVersion,
},
TeamAnalytics.provider?.capture(event, {
...properties,
os: TeamAnalytics.os,
extensionVersion: TeamAnalytics.extensionVersion,
});
}
static shutdownPosthogClient() {
TeamAnalytics.client?.shutdown();
}
static async setup(
config: Analytics,
uniqueId: string,
@ -32,17 +38,12 @@ export class TeamAnalytics {
TeamAnalytics.os = os.platform();
TeamAnalytics.extensionVersion = extensionVersion;
if (!config || !config.clientKey || !config.url) {
TeamAnalytics.client = undefined;
if (!config) {
await TeamAnalytics.provider?.shutdown();
TeamAnalytics.provider = undefined;
} else {
try {
const { PostHog } = await import("posthog-node");
TeamAnalytics.client = new PostHog(config.clientKey, {
host: config.url,
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(config, uniqueId);
}
}
}

View file

@ -0,0 +1,17 @@
import { Analytics } from "@continuedev/config-types";
import { IAnalyticsProvider } from "./IAnalyticsProvider";
export default class ElasticAnalyticsProvider implements IAnalyticsProvider {
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
throw new Error("Method not implemented.");
}
async setup(config: Analytics, uniqueId: string): Promise<void> {
throw new Error("Method not implemented.");
}
async shutdown(): Promise<void> {}
}

View file

@ -0,0 +1,11 @@
import { Analytics } from "@continuedev/config-types";
export interface AnalyticsMetadata {
extensionVersion: string;
}
export interface IAnalyticsProvider {
capture(event: string, properties: { [key: string]: any }): Promise<void>;
setup(config: Analytics, uniqueId: string): Promise<void>;
shutdown(): Promise<void>;
}

View file

@ -0,0 +1,37 @@
import { Analytics } from "@continuedev/config-types";
import { IAnalyticsProvider } from "./IAnalyticsProvider";
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
client?: any;
uniqueId?: string;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
this.client?.capture({
distinctId: this.uniqueId,
event,
properties,
});
}
async setup(config: Analytics, uniqueId: string): Promise<void> {
if (!config || !config.clientKey || !config.url) {
this.client = undefined;
} else {
try {
this.uniqueId = uniqueId;
const { PostHog } = await import("posthog-node");
this.client = new PostHog(config.clientKey, {
host: config.url,
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
}
async shutdown(): Promise<void> {}
}

View file

@ -1,6 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import type {
ContextItemId,
EmbeddingsProvider,
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
@ -16,9 +17,9 @@ import {
import { createNewPromptFile } from "./config/promptFile.js";
import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
import { ContinueServerClient } from "./continueServer/stubs/client.js";
import { ControlPlaneClient } from "./control-plane/client";
import { ControlPlaneClient } from "./control-plane/client.js";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js";
import { DocsService } from "./indexing/docs/DocsService";
import { DocsService } from "./indexing/docs/DocsService.js";
import TransformersJsEmbeddingsProvider from "./indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import Ollama from "./llm/llms/Ollama.js";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -65,6 +66,14 @@ export class Core {
return this.messenger.invoke(messageType, data);
}
send<T extends keyof FromCoreProtocol>(
messageType: T,
data: FromCoreProtocol[T][0],
messageId?: string,
): string {
return this.messenger.send(messageType, data);
}
// TODO: It shouldn't actually need an IDE type, because this can happen
// through the messenger (it does in the case of any non-VS Code IDEs already)
constructor(
@ -73,20 +82,35 @@ export class Core {
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
});
this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise);
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.onWrite,
this.controlPlaneClient,
);
this.configHandler.onConfigUpdate(
(() => this.messenger.send("configUpdate", undefined)).bind(this),
);
this.configHandler.onConfigUpdate(async ({ embeddingsProvider }) => {
if (
await this.shouldReindexDocsOnNewEmbeddingsProvider(
embeddingsProvider.id,
)
) {
await this.reindexDocsOnNewEmbeddingsProvider(embeddingsProvider);
}
});
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
this.messenger.send("didChangeAvailableProfiles", { profiles }),
);
@ -117,9 +141,23 @@ export class Core {
continueServerClient,
),
);
// Index on initialization
this.ide
.getWorkspaceDirs()
.then((dirs) => this.refreshCodebaseIndex(dirs));
.then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
await this.messenger.request("indexProgress", {
progress: 100,
desc: "Initial Indexing Skipped",
status: "paused",
});
return;
}
this.refreshCodebaseIndex(dirs);
});
});
const getLlm = async () => {
@ -221,19 +259,8 @@ export class Core {
// Context providers
on("context/addDocs", async (msg) => {
const siteIndexingConfig: SiteIndexingConfig = {
startUrl: msg.data.startUrl,
rootUrl: msg.data.rootUrl,
title: msg.data.title,
maxDepth: msg.data.maxDepth,
faviconUrl: new URL("/favicon.ico", msg.data.rootUrl).toString(),
};
await this.getEmbeddingsProviderAndIndexDoc(msg.data);
for await (const _ of this.docsService.indexAndAdd(
siteIndexingConfig,
new TransformersJsEmbeddingsProvider(),
)) {
}
this.ide.infoPopup(`Successfully indexed ${msg.data.title}`);
this.messenger.send("refreshSubmenuItems", undefined);
});
@ -248,11 +275,18 @@ export class Core {
(provider) => provider.description.title === "docs",
);
const siteIndexingOptions: SiteIndexingConfig[] = provider ?
(mProvider => mProvider?.options?.sites || [])({ ...provider }) :
[];
if (!provider) {
this.ide.infoPopup("No docs in configuration");
return;
}
const siteIndexingOptions: SiteIndexingConfig[] = ((mProvider) =>
mProvider?.options?.sites || [])({ ...provider });
for (const site of siteIndexingOptions) {
await this.getEmbeddingsProviderAndIndexDoc(site, msg.data.reIndex);
}
await this.indexDocs(siteIndexingOptions, msg.data.reIndex);
this.ide.infoPopup("Docs indexing completed");
});
on("context/loadSubmenuItems", async (msg) => {
@ -602,7 +636,7 @@ export class Core {
});
on("index/forceReIndex", async (msg) => {
const dirs = msg.data ? [msg.data] : await this.ide.getWorkspaceDirs();
this.refreshCodebaseIndex(dirs);
await this.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {
new GlobalContext().update("indexingPaused", msg.data);
@ -619,6 +653,9 @@ export class Core {
on("didChangeSelectedProfile", (msg) => {
this.configHandler.setSelectedProfile(msg.data.id);
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
});
}
private indexingCancellationController: AbortController | undefined;
@ -635,17 +672,97 @@ export class Core {
this.messenger.request("indexProgress", update);
this.indexingState = update;
}
this.messenger.send("refreshSubmenuItems", undefined);
}
private async indexDocs(sites: SiteIndexingConfig[], reIndex: boolean): Promise<void> {
for (const site of sites) {
for await (const update of this.docsService.indexAndAdd(site, new TransformersJsEmbeddingsProvider(), reIndex)) {
// Temporary disabled posting progress updates to the UI due to
// possible collision with code indexing progress updates.
private async shouldReindexDocsOnNewEmbeddingsProvider(
curEmbeddingsProviderId: EmbeddingsProvider["id"],
): Promise<boolean> {
const ideInfo = await this.ide.getIdeInfo();
const isJetBrainsAndPreIndexedDocsProvider =
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
ideInfo,
curEmbeddingsProviderId,
);
// this.messenger.request("indexProgress", update);
// this.indexingState = update;
}
if (isJetBrainsAndPreIndexedDocsProvider) {
this.ide.errorPopup(
`${DocsService.preIndexedDocsEmbeddingsProvider.id} cannot be used as an embeddings provider with JetBrains. Please select a different embeddings provider.`,
);
this.globalContext.update(
"curEmbeddingsProviderId",
curEmbeddingsProviderId,
);
return false;
}
const lastEmbeddingsProviderId = this.globalContext.get(
"curEmbeddingsProviderId",
);
if (!lastEmbeddingsProviderId) {
// If it's the first time we're setting the `curEmbeddingsProviderId`
// global state, we don't need to reindex docs
this.globalContext.update(
"curEmbeddingsProviderId",
curEmbeddingsProviderId,
);
return false;
}
return lastEmbeddingsProviderId !== curEmbeddingsProviderId;
}
private async getEmbeddingsProviderAndIndexDoc(
site: SiteIndexingConfig,
reIndex: boolean = false,
): Promise<void> {
const config = await this.config();
const { embeddingsProvider } = config;
for await (const update of this.docsService.indexAndAdd(
site,
embeddingsProvider,
reIndex,
)) {
// Temporary disabled posting progress updates to the UI due to
// possible collision with code indexing progress updates.
// this.messenger.request("indexProgress", update);
// this.indexingState = update;
}
}
private async reindexDocsOnNewEmbeddingsProvider(
embeddingsProvider: EmbeddingsProvider,
) {
const docs = await this.docsService.list();
if (docs.length === 0) {
return;
}
this.ide.infoPopup("Reindexing docs with new embeddings provider");
for (const { title, baseUrl } of docs) {
await this.docsService.delete(baseUrl);
const generator = this.docsService.indexAndAdd(
{ title, startUrl: baseUrl, rootUrl: baseUrl },
embeddingsProvider,
);
while (!(await generator.next()).done) {}
}
// Important that this only is invoked after we have successfully
// cleared and reindex the docs so that the table cannot end up in an
// invalid state.
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
this.ide.infoPopup("Completed reindexing of all docs");
}
}

9
core/index.d.ts vendored
View file

@ -422,6 +422,8 @@ export interface IdeSettings {
remoteConfigSyncPeriod: number;
userToken: string;
enableControlServerBeta: boolean;
pauseCodebaseIndexOnStart: boolean
enableDebugLogs: boolean
}
export interface IDE {
@ -759,7 +761,12 @@ export interface EmbeddingsProvider {
embed(chunks: string[]): Promise<number[][]>;
}
export type RerankerName = "cohere" | "voyage" | "llm" | "free-trial" | "huggingface-tei";
export type RerankerName =
| "cohere"
| "voyage"
| "llm"
| "free-trial"
| "huggingface-tei";
export interface RerankerDescription {
name: RerankerName;

View file

@ -6,7 +6,7 @@ import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { CodebaseIndex } from "./types.js";
import { CodebaseIndex, IndexResultType } from "./types.js";
import { walkDir } from "./walkDir.js";
export class PauseToken {
@ -112,7 +112,7 @@ export class CodebaseIndexer {
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, markComplete] = await getComputeDeleteAddRemove(
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
@ -159,6 +159,10 @@ export class CodebaseIndexer {
};
}
lastUpdated.forEach((lastUpdated, path) => {
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
});
completedRelativeExpectedTime += codebaseIndex.relativeExpectedTime;
yield {
progress:

View file

@ -114,6 +114,24 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
handleChunk(chunk);
}
accumulatedProgress =
(i / results.compute.length) * (1 - progressReservedForTagging);
yield {
progress: accumulatedProgress,
desc: `Chunking ${getBasename(item.path)}`,
status: "indexing",
};
markComplete([item], IndexResultType.Compute);
// Insert chunks
for await (const chunk of chunkDocument(
item.path,
contents[i],
this.maxChunkSize,
item.cacheKey,
)) {
handleChunk(chunk);
}
accumulatedProgress =
(i / results.compute.length) * (1 - progressReservedForTagging);
yield {
@ -125,17 +143,20 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
}
// Add tag
for (const item of results.addTag) {
const chunksWithPath = await db.all(
"SELECT * FROM chunks WHERE cacheKey = ?",
[item.cacheKey],
);
const addContents = await Promise.all(
results.addTag.map(({ path }) => this.readFile(path)),
);
for (let i = 0; i < results.addTag.length; i++) {
const item = results.addTag[i];
for (const chunk of chunksWithPath) {
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
chunk.id,
tagString,
]);
// Insert chunks
for await (const chunk of chunkDocument(
item.path,
addContents[i],
this.maxChunkSize,
item.cacheKey,
)) {
handleChunk(chunk);
}
markComplete([item], IndexResultType.AddTag);

View file

@ -3,15 +3,16 @@ import sqlite3 from "sqlite3";
import {
Chunk,
EmbeddingsProvider,
IdeInfo,
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../../index.js";
import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths.js";
import { Article, chunkArticle, pageToArticle } from "./article.js";
import { crawlPage } from "./crawl.js";
import { downloadFromS3, SiteIndexingResults } from "./preIndexed.js";
import { default as configs } from "./preIndexedDocs.js";
import preIndexedDocs from "./preIndexedDocs.js";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
// Purposefully lowercase because lancedb converts
interface LanceDbDocsRow {
@ -29,6 +30,8 @@ interface LanceDbDocsRow {
export class DocsService {
private static instance: DocsService;
private static DOCS_TABLE_NAME = "docs";
public static preIndexedDocsEmbeddingsProvider =
new TransformersJsEmbeddingsProvider();
private _sqliteTable: Database | undefined;
private docsIndexingQueue: Set<string> = new Set();
@ -70,32 +73,35 @@ export class DocsService {
nested = false,
): Promise<Chunk[]> {
const lance = await this.getLanceDb();
const db = await this.getSqliteTable();
const tableNames = await lance.tableNames();
const preIndexedDoc = preIndexedDocs[baseUrl];
const isPreIndexedDoc = !!preIndexedDoc;
let shouldDownloadPreIndexedDoc =
!tableNames.includes(DocsService.DOCS_TABLE_NAME) && isPreIndexedDoc;
const downloadDocs = async () => {
const config = configs.find((config) => config.startUrl === baseUrl);
if (config) {
await this.downloadPreIndexedDocs(embeddingsProviderId, config.title);
return await this.retrieve(
baseUrl,
vector,
nRetrieve,
embeddingsProviderId,
true,
);
}
return undefined;
const downloadAndRetrievePreIndexedDoc = async (
preIndexedDoc: SiteIndexingConfig,
) => {
await this.downloadAndAddPreIndexedDocs(
embeddingsProviderId,
preIndexedDoc.title,
);
return await this.retrieve(
baseUrl,
vector,
nRetrieve,
embeddingsProviderId,
true,
);
};
const tableNames = await lance.tableNames();
if (!tableNames.includes(DocsService.DOCS_TABLE_NAME)) {
const downloaded = await downloadDocs();
if (downloaded) {
return downloaded;
}
if (shouldDownloadPreIndexedDoc) {
return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!);
}
const table = await lance.openTable(DocsService.DOCS_TABLE_NAME);
let docs: LanceDbDocsRow[] = await table
.search(vector)
.limit(nRetrieve)
@ -104,11 +110,11 @@ export class DocsService {
docs = docs.filter((doc) => doc.baseurl === baseUrl);
if ((!docs || docs.length === 0) && !nested) {
const downloaded = await downloadDocs();
if (downloaded) {
return downloaded;
}
shouldDownloadPreIndexedDoc =
(!docs || docs.length === 0) && !nested && isPreIndexedDoc;
if (shouldDownloadPreIndexedDoc) {
return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!);
}
return docs.map((doc) => ({
@ -184,7 +190,7 @@ export class DocsService {
return !!doc;
}
private async downloadPreIndexedDocs(
private async downloadAndAddPreIndexedDocs(
embeddingsProviderId: string,
title: string,
) {
@ -264,7 +270,8 @@ export class DocsService {
const embeddings: number[][] = [];
// Create embeddings of retrieved articles
console.log("Creating Embeddings for ", articles.length, " articles");
console.log(`Creating embeddings for ${articles.length} articles`);
for (let i = 0; i < articles.length; i++) {
const article = articles[i];
yield {
@ -313,4 +320,15 @@ export class DocsService {
status: "done",
};
}
public isJetBrainsAndPreIndexedDocsProvider(
ideInfo: IdeInfo,
embeddingsProviderId: EmbeddingsProvider["id"],
): boolean {
const isJetBrains = ideInfo.ideType === "jetbrains";
const isPreIndexedDocsProvider =
embeddingsProviderId === DocsService.preIndexedDocsEmbeddingsProvider.id;
return isJetBrains && isPreIndexedDocsProvider;
}
}

View file

@ -16,7 +16,7 @@ const IGNORE_PATHS_ENDING_IN = [
"changelog.html",
];
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
const markdownRegex = new RegExp(/\.(md|mdx)$/);
async function getDefaultBranch(owner: string, repo: string): Promise<string> {
const octokit = new Octokit({ auth: undefined });
@ -53,7 +53,10 @@ async function crawlGithubRepo(baseUrl: URL) {
);
const paths = tree.data.tree
.filter((file: any) => file.type === "blob" && file.path?.endsWith(".md"))
.filter(
(file: any) =>
file.type === "blob" && markdownRegex.test(file.path ?? ""),
)
.map((file: any) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
@ -142,7 +145,10 @@ export async function* crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log("Starting crawl from: ", url, " - Max Depth: ", maxDepth);
console.log(
`Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = splitUrl(url);
let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }];

View file

@ -1,301 +1,305 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { SiteIndexingConfig } from "../../index.js";
const configs: SiteIndexingConfig[] = [
{
const preIndexedDocs: Record<
SiteIndexingConfig["startUrl"],
SiteIndexingConfig
> = {
"https://jinja.palletsprojects.com/en/3.1.x/": {
title: "Jinja",
startUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
faviconUrl: "https://jinja.palletsprojects.com/favicon.ico",
},
{
"https://react.dev/reference/": {
title: "React",
startUrl: "https://react.dev/reference/",
rootUrl: "https://react.dev/reference/",
faviconUrl: "https://react.dev/favicon.ico",
},
{
"https://posthog.com/docs": {
title: "PostHog",
startUrl: "https://posthog.com/docs",
rootUrl: "https://posthog.com/docs",
faviconUrl: "https://posthog.com/favicon.ico",
},
{
"https://expressjs.com/en/5x/api.html": {
title: "Express",
startUrl: "https://expressjs.com/en/5x/api.html",
rootUrl: "https://expressjs.com/en/5x/",
faviconUrl: "https://expressjs.com/favicon.ico",
},
{
"https://platform.openai.com/docs/": {
title: "OpenAI",
startUrl: "https://platform.openai.com/docs/",
rootUrl: "https://platform.openai.com/docs/",
faviconUrl: "https://platform.openai.com/favicon.ico",
},
{
"https://www.prisma.io/docs": {
title: "Prisma",
startUrl: "https://www.prisma.io/docs",
rootUrl: "https://www.prisma.io/docs",
faviconUrl: "https://www.prisma.io/favicon.ico",
},
{
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html": {
title: "Boto3",
startUrl:
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html",
rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/",
faviconUrl: "https://boto3.amazonaws.com/favicon.ico",
},
{
"https://pytorch.org/docs/stable/": {
title: "Pytorch",
startUrl: "https://pytorch.org/docs/stable/",
rootUrl: "https://pytorch.org/docs/stable/",
faviconUrl: "https://pytorch.org/favicon.ico",
},
{
"https://redis.io/docs/": {
title: "Redis",
startUrl: "https://redis.io/docs/",
rootUrl: "https://redis.io/docs/",
faviconUrl: "https://redis.io/favicon.ico",
},
{
"https://axios-http.com/docs/intro": {
title: "Axios",
startUrl: "https://axios-http.com/docs/intro",
rootUrl: "https://axios-http.com/docs",
faviconUrl: "https://axios-http.com/favicon.ico",
},
{
"https://redwoodjs.com/docs/introduction": {
title: "Redwood JS",
startUrl: "https://redwoodjs.com/docs/introduction",
rootUrl: "https://redwoodjs.com/docs",
faviconUrl: "https://redwoodjs.com/favicon.ico",
},
{
"https://graphql.org/learn/": {
title: "GraphQL",
startUrl: "https://graphql.org/learn/",
rootUrl: "https://graphql.org/learn/",
faviconUrl: "https://graphql.org/favicon.ico",
},
{
"https://www.typescriptlang.org/docs/": {
title: "Typescript",
startUrl: "https://www.typescriptlang.org/docs/",
rootUrl: "https://www.typescriptlang.org/docs/",
faviconUrl: "https://www.typescriptlang.org/favicon.ico",
},
{
"https://jestjs.io/docs/getting-started": {
title: "Jest",
startUrl: "https://jestjs.io/docs/getting-started",
rootUrl: "https://jestjs.io/docs",
faviconUrl: "https://jestjs.io/favicon.ico",
},
{
"https://tailwindcss.com/docs/installation": {
title: "Tailwind CSS",
startUrl: "https://tailwindcss.com/docs/installation",
rootUrl: "https://tailwindcss.com/docs",
faviconUrl: "https://tailwindcss.com/favicon.ico",
},
{
"https://vuejs.org/guide/introduction.html": {
title: "Vue.js",
startUrl: "https://vuejs.org/guide/introduction.html",
rootUrl: "https://vuejs.org",
faviconUrl: "https://vuejs.org/favicon.ico",
},
{
"https://svelte.dev/docs/introduction": {
title: "Svelte",
startUrl: "https://svelte.dev/docs/introduction",
rootUrl: "https://svelte.dev/docs",
faviconUrl: "https://svelte.dev/favicon.ico",
},
{
"https://docs.github.com/en/actions": {
title: "GitHub Actions",
startUrl: "https://docs.github.com/en/actions",
rootUrl: "https://docs.github.com/en/actions",
faviconUrl: "https://docs.github.com/favicon.ico",
},
{
"https://nodejs.org/docs/latest/api/": {
title: "NodeJS",
startUrl: "https://nodejs.org/docs/latest/api/",
rootUrl: "https://nodejs.org/docs/latest/api/",
faviconUrl: "https://nodejs.org/favicon.ico",
},
{
"https://socket.io/docs/v4/": {
title: "Socket.io",
startUrl: "https://socket.io/docs/v4/",
rootUrl: "https://socket.io/docs/v4/",
faviconUrl: "https://socket.io/favicon.ico",
},
{
"https://docs.gradle.org/current/userguide/userguide.html": {
title: "Gradle",
startUrl: "https://docs.gradle.org/current/userguide/userguide.html",
rootUrl: "https://docs.gradle.org/current",
faviconUrl: "https://docs.gradle.org/favicon.ico",
},
{
"https://redux-toolkit.js.org/introduction/getting-started": {
title: "Redux Toolkit",
startUrl: "https://redux-toolkit.js.org/introduction/getting-started",
rootUrl: "https://redux-toolkit.js.org",
faviconUrl: "https://redux-toolkit.js.org/favicon.ico",
},
{
"https://docs.trychroma.com/": {
title: "Chroma",
startUrl: "https://docs.trychroma.com/",
rootUrl: "https://docs.trychroma.com/",
faviconUrl: "https://docs.trychroma.com/favicon.ico",
},
{
"https://www.sqlite.org/docs.html": {
title: "SQLite",
startUrl: "https://www.sqlite.org/docs.html",
rootUrl: "https://www.sqlite.org",
faviconUrl: "https://www.sqlite.org/favicon.ico",
},
{
"https://redux.js.org/introduction/getting-started": {
title: "Redux",
startUrl: "https://redux.js.org/introduction/getting-started",
rootUrl: "https://redux.js.org",
faviconUrl: "https://redux.js.org/favicon.ico",
},
{
"https://prettier.io/docs/en/": {
title: "Prettier",
startUrl: "https://prettier.io/docs/en/",
rootUrl: "https://prettier.io/docs/en/",
faviconUrl: "https://prettier.io/favicon.ico",
},
{
"https://code.visualstudio.com/api": {
title: "VS Code Extension API",
startUrl: "https://code.visualstudio.com/api",
rootUrl: "https://code.visualstudio.com/api",
faviconUrl: "https://code.visualstudio.com/favicon.ico",
},
{
"https://docs.continue.dev/intro": {
title: "Continue",
startUrl: "https://docs.continue.dev/intro",
rootUrl: "https://docs.continue.dev",
faviconUrl: "https://docs.continue.dev/favicon.ico",
},
{
"https://api.jquery.com/": {
title: "jQuery",
startUrl: "https://api.jquery.com/",
rootUrl: "https://api.jquery.com/",
faviconUrl: "https://api.jquery.com/favicon.ico",
},
{
"https://docs.python.org/3/": {
title: "Python",
startUrl: "https://docs.python.org/3/",
rootUrl: "https://docs.python.org/3/",
faviconUrl: "https://docs.python.org/favicon.ico",
},
{
"https://doc.rust-lang.org/book/": {
title: "Rust",
startUrl: "https://doc.rust-lang.org/book/",
rootUrl: "https://doc.rust-lang.org/book/",
faviconUrl: "https://doc.rust-lang.org/favicon.ico",
},
{
"https://plugins.jetbrains.com/docs/intellij/welcome.html": {
title: "IntelliJ Platform SDK",
startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html",
rootUrl: "https://plugins.jetbrains.com/docs/intellij",
faviconUrl: "https://plugins.jetbrains.com/favicon.ico",
},
{
"https://docs.docker.com/": {
title: "Docker",
startUrl: "https://docs.docker.com/",
rootUrl: "https://docs.docker.com/",
faviconUrl: "https://docs.docker.com/favicon.ico",
},
{
"https://docs.npmjs.com/": {
title: "NPM",
startUrl: "https://docs.npmjs.com/",
rootUrl: "https://docs.npmjs.com/",
faviconUrl: "https://docs.npmjs.com/favicon.ico",
},
{
"https://tiptap.dev/docs/editor/introduction": {
title: "TipTap",
startUrl: "https://tiptap.dev/docs/editor/introduction",
rootUrl: "https://tiptap.dev/docs",
faviconUrl: "https://tiptap.dev/favicon.ico",
},
{
"https://esbuild.github.io/": {
title: "esbuild",
startUrl: "https://esbuild.github.io/",
rootUrl: "https://esbuild.github.io/",
faviconUrl: "https://esbuild.github.io/favicon.ico",
},
{
"https://tree-sitter.github.io/tree-sitter/": {
title: "Tree Sitter",
startUrl: "https://tree-sitter.github.io/tree-sitter/",
rootUrl: "https://tree-sitter.github.io/tree-sitter/",
faviconUrl: "https://tree-sitter.github.io/favicon.ico",
},
{
"https://docs.netlify.com/": {
title: "Netlify",
startUrl: "https://docs.netlify.com/",
rootUrl: "https://docs.netlify.com/",
faviconUrl: "https://docs.netlify.com/favicon.ico",
},
{
"https://replicate.com/docs": {
title: "Replicate",
startUrl: "https://replicate.com/docs",
rootUrl: "https://replicate.com/docs",
faviconUrl: "https://replicate.com/favicon.ico",
},
{
"https://www.w3schools.com/html/default.asp": {
title: "HTML",
startUrl: "https://www.w3schools.com/html/default.asp",
rootUrl: "https://www.w3schools.com/html",
faviconUrl: "https://www.w3schools.com/favicon.ico",
},
{
"https://www.w3schools.com/css/default.asp": {
title: "CSS",
startUrl: "https://www.w3schools.com/css/default.asp",
rootUrl: "https://www.w3schools.com/css",
faviconUrl: "https://www.w3schools.com/favicon.ico",
},
{
"https://python.langchain.com/docs/get_started/introduction": {
title: "Langchain",
startUrl: "https://python.langchain.com/docs/get_started/introduction",
rootUrl: "https://python.langchain.com/docs",
faviconUrl: "https://python.langchain.com/favicon.ico",
},
{
"https://developer.woocommerce.com/docs/": {
title: "WooCommerce",
startUrl: "https://developer.woocommerce.com/docs/",
rootUrl: "https://developer.woocommerce.com/docs/",
faviconUrl: "https://developer.woocommerce.com/favicon.ico",
},
{
"https://developer.wordpress.org/reference/": {
title: "WordPress",
startUrl: "https://developer.wordpress.org/reference/",
rootUrl: "https://developer.wordpress.org/reference/",
faviconUrl: "https://developer.wordpress.org/favicon.ico",
},
{
"https://doc.qt.io/qtforpython-6/quickstart.html": {
title: "PySide6",
startUrl: "https://doc.qt.io/qtforpython-6/quickstart.html",
rootUrl: "https://doc.qt.io/qtforpython-6/api.html",
faviconUrl: "https://doc.qt.io/favicon.ico",
},
{
"https://getbootstrap.com/docs/5.3/getting-started/introduction/": {
title: "Bootstrap",
startUrl: "https://getbootstrap.com/docs/5.3/getting-started/introduction/",
rootUrl: "https://getbootstrap.com/docs/5.3/",
faviconUrl: "https://getbootstrap.com/favicon.ico",
},
{
"https://alpinejs.dev/start-here": {
title: "Alpine.js",
startUrl: "https://alpinejs.dev/start-here",
rootUrl: "https://alpinejs.dev/",
faviconUrl: "https://alpinejs.dev/favicon.ico",
},
{
"https://learn.microsoft.com/en-us/dotnet/csharp/": {
title: "C# Language Reference",
startUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
rootUrl: "https://learn.microsoft.com/en-us/dotnet/csharp/",
faviconUrl: "https://learn.microsoft.com/favicon.ico",
},
{
"https://docs.godotengine.org/en/latest/": {
title: "Godot",
startUrl: "https://docs.godotengine.org/en/latest/",
rootUrl: "https://docs.godotengine.org/en/latest/",
faviconUrl: "https://godotengine.org/favicon.ico",
},
];
};
export default configs;
export default preIndexedDocs;

View file

@ -44,6 +44,36 @@ export class SqliteDb {
artifactId STRING NOT NULL
)`,
);
// Delete duplicate rows from tag_catalog
await db.exec(`
DELETE FROM tag_catalog
WHERE id NOT IN (
SELECT MIN(id)
FROM tag_catalog
GROUP BY dir, branch, artifactId, path, cacheKey
)
`);
// Delete duplicate rows from global_cache
await db.exec(`
DELETE FROM global_cache
WHERE id NOT IN (
SELECT MIN(id)
FROM global_cache
GROUP BY cacheKey, dir, branch, artifactId
)
`);
// Add unique constraints if they don't exist
await db.exec(
`CREATE UNIQUE INDEX IF NOT EXISTS idx_tag_catalog_unique
ON tag_catalog(dir, branch, artifactId, path, cacheKey)`,
);
await db.exec(
`CREATE UNIQUE INDEX IF NOT EXISTS idx_global_cache_unique
ON global_cache(cacheKey, dir, branch, artifactId)`,
);
}
private static indexSqlitePath = getIndexSqlitePath();
@ -90,14 +120,24 @@ enum AddRemoveResultType {
Remove = "remove",
UpdateNewVersion = "updateNewVersion",
UpdateOldVersion = "updateOldVersion",
UpdateLastUpdated = "updateLastUpdated",
Compute = "compute"
}
async function getAddRemoveForTag(
tag: IndexTag,
currentFiles: LastModifiedMap,
readFile: (path: string) => Promise<string>,
): Promise<[PathAndCacheKey[], PathAndCacheKey[], MarkCompleteCallback]> {
): Promise<
[
PathAndCacheKey[],
PathAndCacheKey[],
PathAndCacheKey[],
MarkCompleteCallback,
]
> {
const newLastUpdatedTimestamp = Date.now();
const files = { ...currentFiles };
const saved = await getSavedItemsForTag(tag);
@ -105,35 +145,41 @@ async function getAddRemoveForTag(
const updateNewVersion: PathAndCacheKey[] = [];
const updateOldVersion: PathAndCacheKey[] = [];
const remove: PathAndCacheKey[] = [];
const updateLastUpdated: PathAndCacheKey[] = [];
for (const item of saved) {
const { lastUpdated, ...pathAndCacheKey } = item;
if (currentFiles[item.path] === undefined) {
if (files[item.path] === undefined) {
// Was indexed, but no longer exists. Remove
remove.push(pathAndCacheKey);
} else {
// Exists in old and new, so determine whether it was updated
if (lastUpdated < currentFiles[item.path]) {
if (lastUpdated < files[item.path]) {
// Change was made after last update
updateNewVersion.push({
path: pathAndCacheKey.path,
cacheKey: calculateHash(await readFile(pathAndCacheKey.path)),
});
updateOldVersion.push(pathAndCacheKey);
const newHash = calculateHash(await readFile(pathAndCacheKey.path));
if (pathAndCacheKey.cacheKey !== newHash) {
updateNewVersion.push({
path: pathAndCacheKey.path,
cacheKey: newHash,
});
updateOldVersion.push(pathAndCacheKey);
} else {
updateLastUpdated.push(pathAndCacheKey);
}
} else {
// Already updated, do nothing
}
// Remove so we can check leftovers afterward
delete currentFiles[item.path];
delete files[item.path];
}
}
// Any leftover in current files need to be added
add.push(
...(await Promise.all(
Object.keys(currentFiles).map(async (path) => {
Object.keys(files).map(async (path) => {
const fileContents = await readFile(path);
return { path, cacheKey: calculateHash(fileContents) };
}),
@ -143,18 +189,43 @@ async function getAddRemoveForTag(
// Create the markComplete callback function
const db = await SqliteDb.get();
const itemToAction: {
[key: string]: [PathAndCacheKey, AddRemoveResultType];
} = {};
[key in AddRemoveResultType]: PathAndCacheKey[];
} = {
[AddRemoveResultType.Add]: [],
[AddRemoveResultType.Remove]: [],
[AddRemoveResultType.UpdateNewVersion]: [],
[AddRemoveResultType.UpdateOldVersion]: [],
[AddRemoveResultType.UpdateLastUpdated]: [],
[AddRemoveResultType.Compute]: [],
};
async function markComplete(items: PathAndCacheKey[], _: IndexResultType) {
const actions = items.map(
(item) =>
itemToAction[
JSON.stringify({ path: item.path, cacheKey: item.cacheKey })
],
);
for (const [{ path, cacheKey }, resultType] of actions) {
switch (resultType) {
async function markComplete(
items: PathAndCacheKey[],
resultType: IndexResultType,
) {
const addRemoveResultType =
mapIndexResultTypeToAddRemoveResultType(resultType);
const actionItems = itemToAction[addRemoveResultType];
if (!actionItems) {
console.warn(`No action items found for result type: ${resultType}`);
return;
}
for (const item of items) {
const { path, cacheKey } = item;
switch (addRemoveResultType) {
case AddRemoveResultType.Compute:
await db.run(
"REPLACE INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
path,
cacheKey,
newLastUpdatedTimestamp,
tag.directory,
tag.branch,
tag.artifactId,
);
break;
case AddRemoveResultType.Add:
await db.run(
"INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
@ -182,6 +253,7 @@ async function getAddRemoveForTag(
tag.artifactId,
);
break;
case AddRemoveResultType.UpdateLastUpdated:
case AddRemoveResultType.UpdateNewVersion:
await db.run(
`UPDATE tag_catalog SET
@ -208,27 +280,22 @@ async function getAddRemoveForTag(
}
for (const item of updateNewVersion) {
itemToAction[JSON.stringify(item)] = [
item,
AddRemoveResultType.UpdateNewVersion,
];
itemToAction[AddRemoveResultType.UpdateNewVersion].push(item);
}
for (const item of add) {
itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Add];
itemToAction[AddRemoveResultType.Add].push(item);
}
for (const item of updateOldVersion) {
itemToAction[JSON.stringify(item)] = [
item,
AddRemoveResultType.UpdateOldVersion,
];
itemToAction[AddRemoveResultType.UpdateOldVersion].push(item);
}
for (const item of remove) {
itemToAction[JSON.stringify(item)] = [item, AddRemoveResultType.Remove];
itemToAction[AddRemoveResultType.Remove].push(item);
}
return [
[...add, ...updateNewVersion],
[...remove, ...updateOldVersion],
updateLastUpdated,
markComplete,
];
}
@ -255,13 +322,31 @@ function calculateHash(fileContents: string): string {
return hash.digest("hex");
}
function mapIndexResultTypeToAddRemoveResultType(
resultType: IndexResultType,
): AddRemoveResultType {
switch (resultType) {
case "updateLastUpdated":
return AddRemoveResultType.UpdateLastUpdated;
case "compute":
return AddRemoveResultType.Compute;
case "addTag":
return AddRemoveResultType.Add;
case "del":
case "removeTag":
return AddRemoveResultType.Remove;
default:
throw new Error(`Unexpected result type: ${resultType}`);
}
}
export async function getComputeDeleteAddRemove(
tag: IndexTag,
currentFiles: LastModifiedMap,
readFile: (path: string) => Promise<string>,
repoName: string | undefined,
): Promise<[RefreshIndexResults, MarkCompleteCallback]> {
const [add, remove, markComplete] = await getAddRemoveForTag(
): Promise<[RefreshIndexResults, PathAndCacheKey[], MarkCompleteCallback]> {
const [add, remove, lastUpdated, markComplete] = await getAddRemoveForTag(
tag,
currentFiles,
readFile,
@ -305,6 +390,7 @@ export async function getComputeDeleteAddRemove(
return [
results,
lastUpdated,
async (items, resultType) => {
// Update tag catalog
markComplete(items, resultType);
@ -347,15 +433,15 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
_: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const add = [...results.compute, ...results.addTag];
const add = results.addTag;
const remove = [...results.del, ...results.removeTag];
await Promise.all([
...add.map(({ cacheKey }) => {
return this.computeOrAddTag(cacheKey, tag);
}),
...remove.map(({ cacheKey }) => {
return this.deleteOrRemoveTag(cacheKey, tag);
}),
...add.map(({ cacheKey }) => {
return this.computeOrAddTag(cacheKey, tag);
}),
]);
yield { progress: 1, desc: "Done updating global cache", status: "done" };
}

View file

@ -5,6 +5,7 @@ export enum IndexResultType {
Delete = "del",
AddTag = "addTag",
RemoveTag = "removeTag",
UpdateLastUpdated = "updateLastUpdated"
}
export type MarkCompleteCallback = (

View file

@ -1,17 +1,15 @@
import { EventEmitter } from "events";
import { Minimatch } from "minimatch";
import path from "node:path";
import { FileType, IDE } from "../index.js";
import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES } from "./ignore.js";
import { FileType, IDE } from "../index.d.js";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
} from "./ignore.js";
export interface WalkerOptions {
isSymbolicLink?: boolean;
path?: string;
ignoreFiles?: string[];
parent?: Walker | null;
includeEmpty?: boolean;
follow?: boolean;
exact?: boolean;
onlyDirs?: boolean;
returnRelativePaths?: boolean;
additionalIgnoreRules?: string[];
@ -19,314 +17,194 @@ export interface WalkerOptions {
type Entry = [string, FileType];
class Walker extends EventEmitter {
isSymbolicLink: boolean;
path: string;
basename: string;
ignoreFiles: string[];
ignoreRules: { [key: string]: Minimatch[] };
parent: Walker | null;
includeEmpty: boolean;
root: string;
follow: boolean;
result: Set<string>;
entries: Entry[] | null;
sawError: boolean;
exact: boolean | undefined;
onlyDirs: boolean | undefined;
constructor(opts: WalkerOptions = {}, protected readonly ide: IDE) {
super(opts as any);
this.isSymbolicLink = opts.isSymbolicLink || false;
this.path = opts.path || process.cwd();
this.basename = path.basename(this.path);
this.ignoreFiles = [...(opts.ignoreFiles || [".ignore"]), ".defaultignore"];
this.ignoreRules = {};
this.parent = opts.parent || null;
this.includeEmpty = !!opts.includeEmpty;
this.root = this.parent ? this.parent.root : this.path;
this.follow = !!opts.follow;
this.result = this.parent ? this.parent.result : new Set();
this.entries = null;
this.sawError = false;
this.exact = opts.exact;
this.onlyDirs = opts.onlyDirs;
// helper struct used for the DFS walk
type WalkableEntry = {
relPath: string;
absPath: string;
type: FileType;
entry: Entry;
};
if (opts.additionalIgnoreRules) {
this.addIgnoreRules(opts.additionalIgnoreRules);
}
// helper struct used for the DFS walk
type WalkContext = {
walkableEntry: WalkableEntry;
ignoreFiles: IgnoreFile[];
};
class IgnoreFile {
private _rules: Minimatch[];
constructor(
public path: string,
public content: string,
) {
this.path = path;
this.content = content;
this._rules = this.contentToRules(content);
}
sort(a: string, b: string): number {
return a.localeCompare(b, "en");
public get rules() {
return this._rules;
}
emit(ev: string, data: any): boolean {
let ret = false;
if (!(this.sawError && ev === "error")) {
if (ev === "error") {
this.sawError = true;
} else if (ev === "done" && !this.parent) {
data = (Array.from(data) as any)
.map((e: string) => (/^@/.test(e) ? `./${e}` : e))
.sort(this.sort);
this.result = new Set(data);
}
if (ev === "error" && this.parent) {
ret = this.parent.emit("error", data);
} else {
ret = super.emit(ev, data);
}
}
return ret;
}
async *start() {
try {
const entries = await this.ide.listDir(this.path);
for await (const result of this.onReadDir(entries)) {
yield result;
}
} catch (err) {
this.emit("error", err);
}
}
isIgnoreFile(e: Entry): boolean {
const p = e[0];
return p !== "." && p !== ".." && this.ignoreFiles.indexOf(p) !== -1;
}
async *onReadDir(entries: Entry[]) {
this.entries = entries;
if (entries.length === 0) {
if (this.includeEmpty) {
this.result.add(this.path.slice(this.root.length + 1));
}
this.emit("done", this.result);
yield this.result;
} else {
const hasIg = this.entries.some((e) => this.isIgnoreFile(e));
if (hasIg) {
await this.addIgnoreFiles();
}
yield* this.filterEntries();
}
}
async addIgnoreFiles() {
const newIg = this.entries!.filter((e) => this.isIgnoreFile(e));
await Promise.all(newIg.map((e) => this.addIgnoreFile(e)));
}
async addIgnoreFile(fileEntry: Entry) {
const ig = path.resolve(this.path, fileEntry[0]);
try {
const file = await this.ide.readFile(ig);
this.onReadIgnoreFile(fileEntry, file);
} catch (err) {
this.emit("error", err);
}
}
onReadIgnoreFile(file: Entry, data: string): void {
const mmopt = {
private contentToRules(content: string): Minimatch[] {
const options = {
matchBase: true,
dot: true,
flipNegate: true,
nocase: true,
};
const rules = data
return content
.split(/\r?\n/)
.filter((line) => !/^#|^$/.test(line.trim()))
.map((rule) => {
return new Minimatch(rule.trim(), mmopt);
});
.map((l) => l.trim())
.filter((l) => !/^#|^$/.test(l))
.map((l) => new Minimatch(l, options));
}
}
this.ignoreRules[file[0]] = rules;
class DFSWalker {
private readonly path: string;
private readonly ide: IDE;
private readonly options: WalkerOptions;
private readonly ignoreFileNames: Set<string>;
constructor(path: string, ide: IDE, options: WalkerOptions) {
this.path = path;
this.ide = ide;
this.options = options;
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
addIgnoreRules(rules: string[]) {
const mmopt = {
matchBase: true,
dot: true,
flipNegate: true,
nocase: true,
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const root: WalkContext = {
walkableEntry: {
relPath: "",
absPath: this.path,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreFiles: [],
};
const minimatchRules = rules
.filter((line) => !/^#|^$/.test(line.trim()))
.map((rule) => {
return new Minimatch(rule.trim(), mmopt);
});
this.ignoreRules[".defaultignore"] = minimatchRules;
}
async *filterEntries() {
const filtered = (await Promise.all(
this.entries!.map(async (entry) => {
const passFile = await this.filterEntry(entry[0]);
const passDir = await this.filterEntry(entry[0], true);
return passFile || passDir ? [entry, passFile, passDir] : false;
}),
).then((entries) => entries.filter((e) => e))) as [
Entry,
boolean,
boolean,
][];
let entryCount = filtered.length;
if (entryCount === 0) {
this.emit("done", this.result);
yield this.result;
} else {
const then = () => {
if (--entryCount === 0) {
// Otherwise in onlyDirs mode, nothing would be returned
if (this.onlyDirs && this.path !== this.root) {
this.result.add(this.path.slice(this.root.length + 1));
}
this.emit("done", this.result);
}
};
for (const [entry, file, dir] of filtered) {
for await (const statResult of this.stat(entry, file, dir, then)) {
yield statResult;
}
}
}
}
entryIsDirectory(entry: Entry) {
const Directory = 2 as FileType.Directory;
return entry[1] === Directory;
}
entryIsSymlink(entry: Entry) {
const Directory = 64 as FileType.SymbolicLink;
return entry[1] === Directory;
}
async *onstat(entry: Entry, file: boolean, dir: boolean, then: () => void) {
const abs = this.path + "/" + entry[0];
const isSymbolicLink = this.entryIsSymlink(entry);
if (!this.entryIsDirectory(entry)) {
if (file && !this.onlyDirs) {
this.result.add(abs.slice(this.root.length + 1));
}
then();
yield this.result;
} else {
if (dir) {
yield* this.walker(
entry[0],
{ isSymbolicLink, exact: await this.filterEntry(entry[0] + "/") },
then,
);
} else {
then();
yield this.result;
}
}
}
async *stat(
entry: Entry,
file: boolean,
dir: boolean,
then: () => void,
): any {
yield* this.onstat(entry, file, dir, then);
}
walkerOpt(entry: string, opts: Partial<WalkerOptions>): WalkerOptions {
return {
path: this.path + "/" + entry,
parent: this,
ignoreFiles: this.ignoreFiles,
follow: this.follow,
includeEmpty: this.includeEmpty,
onlyDirs: this.onlyDirs,
...opts,
};
}
async *walker(entry: string, opts: Partial<WalkerOptions>, then: () => void) {
const walker = new Walker(this.walkerOpt(entry, opts), this.ide);
walker.on("done", then);
yield* walker.start();
}
async filterEntry(
entry: string,
partial?: boolean,
entryBasename?: string,
): Promise<boolean> {
let included = true;
if (this.parent && this.parent.filterEntry) {
const parentEntry = this.basename + "/" + entry;
const parentBasename = entryBasename || entry;
included = await this.parent.filterEntry(
parentEntry,
partial,
parentBasename,
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreFiles = await this.getIgnoreFilesToApplyInDir(
cur.ignoreFiles,
walkableEntries,
);
if (!included && !this.exact) {
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreFiles)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreFiles: ignoreFiles,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
yield w.relPath;
}
} else {
yield w.relPath;
}
}
}
}
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.absPath);
return entries.map((e) => {
return {
relPath: path.join(walkableEntry.relPath, e[0]),
absPath: path.join(walkableEntry.absPath, e[0]),
type: e[1],
entry: e,
};
});
}
private async getIgnoreFilesToApplyInDir(
parentIgnoreFiles: IgnoreFile[],
walkableEntries: WalkableEntry[],
): Promise<IgnoreFile[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries);
if (ignoreFilesInDir.length === 0) {
return parentIgnoreFiles;
}
return Array.prototype.concat(parentIgnoreFiles, ignoreFilesInDir);
}
private async loadIgnoreFiles(
entries: WalkableEntry[],
): Promise<IgnoreFile[]> {
const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry));
const promises = ignoreEntries.map(async (w) => {
const content = await this.ide.readFile(w.absPath);
return new IgnoreFile(w.relPath, content);
});
return Promise.all(promises);
}
private isIgnoreFile(e: Entry): boolean {
const p = e[0];
return this.ignoreFileNames.has(p);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreFiles: IgnoreFile[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it linksto something outside of the repository and
// we do not want to index it
return false;
}
let relPath = walkableEntry.relPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
if (defaultIgnoreDir.ignores(walkableEntry.relPath)) {
return false;
}
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
}
if (defaultIgnoreFile.ignores(walkableEntry.relPath)) {
return false;
}
relPath = `/${relPath}`;
}
for (const f of this.ignoreFiles) {
if (this.ignoreRules[f]) {
for (const rule of this.ignoreRules[f]) {
if (rule.negate !== included) {
const isRelativeRule =
entryBasename &&
rule.globParts.some(
(part) => part.length <= (part.slice(-1)[0] ? 1 : 2),
);
const match =
rule.match("/" + entry) ||
rule.match(entry) ||
(!!partial &&
(rule.match("/" + entry + "/") ||
rule.match(entry + "/") ||
(rule.negate &&
(rule.match("/" + entry, true) ||
rule.match(entry, true))) ||
(isRelativeRule &&
(rule.match("/" + entryBasename + "/") ||
rule.match(entryBasename + "/") ||
(rule.negate &&
(rule.match("/" + entryBasename, true) ||
rule.match(entryBasename, true)))))));
if (match) {
included = rule.negate;
}
}
let included = true;
for (const ignoreFile of ignoreFiles) {
for (const r of ignoreFile.rules) {
if (r.negate === included) {
// no need to test when the file is already NOT to be included unless this is a negate rule and vice versa
continue;
}
if (r.match(relPath)) {
included = r.negate;
}
}
}
return included;
}
private entryIsDirectory(entry: Entry) {
return entry[1] === (2 as FileType.Directory);
}
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
onlyDirs: false,
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
};
@ -337,39 +215,17 @@ export async function walkDir(
): Promise<string[]> {
let entries: string[] = [];
const options = { ...defaultOptions, ..._options };
const walker = new Walker(
{
path,
ignoreFiles: options.ignoreFiles,
onlyDirs: options.onlyDirs,
follow: true,
includeEmpty: false,
additionalIgnoreRules: options.additionalIgnoreRules,
},
ide,
);
try {
for await (const walkedEntries of walker.start()) {
entries = [...walkedEntries];
}
} catch (err) {
console.error(`Error walking directories: ${err}`);
throw err;
const dfsWalker = new DFSWalker(path, ide, options);
let relativePaths: string[] = [];
for await (const e of dfsWalker.walk()) {
relativePaths.push(e);
}
const relativePaths = entries || [];
if (options?.returnRelativePaths) {
return relativePaths;
}
const pathSep = await ide.pathSep();
if (pathSep === "/") {
return relativePaths.map((p) => path + pathSep + p);
}
return relativePaths.map((p) => path + pathSep + p.split("/").join(pathSep));
}

View file

@ -21,6 +21,10 @@ class ContinueProxy extends OpenAI {
useLegacyCompletionsEndpoint: false,
};
supportsCompletions(): boolean {
return false;
}
supportsFim(): boolean {
return true;
}

View file

@ -11,7 +11,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@continuedev/config-types": "^1.0.8",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
@ -3932,9 +3932,9 @@
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.6.tgz",
"integrity": "sha512-JTlaGtsNW9vfSPcDJBn+I2vcs0wWRFIQcN3sa6pBFg2fj8W6qcMZoYUdzoU/+X+2ZT8OKcbomWfP2+qW0uuy6A==",
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.8.tgz",
"integrity": "sha512-AwrqMK+FSVY1vFaEujVbOI2ETAYmRv6dT9qs/FYhKNCUNIVDbeI0/Mhf6APBVfgK8czrB6XVbY1aJFiZHGqejw==",
"dependencies": {
"zod": "^3.23.8"
}

View file

@ -32,7 +32,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@continuedev/config-types": "^1.0.8",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",

View file

@ -104,12 +104,41 @@ describe("walkDir", () => {
);
});
test("should use gitignore in parent directory for subdirectory", async () => {
const files = [
"a.txt",
"b.py",
"d/",
"d/e.txt",
"d/f.py",
"d/g/",
"d/g/h.ts",
"d/g/i.py",
[".gitignore", "*.py"],
];
addToTestDir(files);
await expectPaths(["a.txt", "d/e.txt", "d/g/h.ts"], ["d/f.py", "d/g/i.py"]);
});
test("should handle leading slash in gitignore", async () => {
const files = [[".gitignore", "/no.txt"], "a.txt", "b.py", "no.txt"];
addToTestDir(files);
await expectPaths(["a.txt", "b.py"], ["no.txt"]);
});
test("should not ignore leading slash when in subfolder", async () => {
const files = [
[".gitignore", "/no.txt"],
"a.txt",
"b.py",
"no.txt",
"sub/",
"sub/no.txt",
];
addToTestDir(files);
await expectPaths(["a.txt", "b.py", "sub/no.txt"], ["no.txt"]);
});
test("should handle multiple .gitignore files in nested structure", async () => {
const files = [
[".gitignore", "*.txt"],
@ -202,7 +231,7 @@ describe("walkDir", () => {
await expectPaths(
["d", "d/g"],
["a.txt", "b.py", "c.ts", "d/e.txt", "d/f.py", "d/g/h.ts"],
{ onlyDirs: true, includeEmpty: true },
{ onlyDirs: true },
);
});

View file

@ -1,10 +1,18 @@
import fs from "node:fs";
import { getGlobalContextFilePath } from "./paths.js";
import { EmbeddingsProvider } from "../index.js";
export type GlobalContextType = {
indexingPaused: boolean;
selectedTabAutocompleteModel: string;
lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string };
/**
* This is needed to handle the case where a JetBrains user has created
* docs embeddings using one provider, and then updates to a new provider.
*
* For VS Code users, it is unnecessary since we use transformers.js by default.
*/
curEmbeddingsProviderId: EmbeddingsProvider["id"];
};
/**

View file

@ -38,6 +38,8 @@ class FileSystemIde implements IDE {
remoteConfigSyncPeriod: 60,
userToken: "",
enableControlServerBeta: false,
pauseCodebaseIndexOnStart: false,
enableDebugLogs: false,
};
}
async getGitHubAuthToken(): Promise<string | undefined> {

View file

@ -10,7 +10,7 @@ Continue can be deeply customized by editing `config.json` and `config.ts` on yo
Currently, you can customize the following:
- [Models](../setup/select-model.md) and [providers](../setup/select-provider.md)
- [Models](../setup/select-model.md) and [Model Providers](../setup/model-providers.md)
- [Context Providers](./context-providers.md)
- [Slash Commands](./slash-commands.md)
- [Other configuration options](../reference/config.mdx)

View file

@ -69,7 +69,7 @@ Groq provides lightning fast inference for open-source LLMs like Llama3, up to t
### ⏩ Other options
The above were only a few examples, but Continue can be used with any LLM or provider. You can find [a full list of providers here](../../setup/select-provider.md).
The above were only a few examples, but Continue can be used with any LLM or provider. You can find [a full list of model providers here](../../setup/model-providers.md).
## Sign in

View file

@ -295,7 +295,7 @@ You can find all existing templates for /edit in [`core/llm/templates/edit.ts`](
## Defining a Custom LLM Provider
If you are using an LLM API that isn't already [supported by Continue](./select-provider.md), and is not an OpenAI-compatible API, you'll need to define a `CustomLLM` object in `config.ts`. This object only requires one of (or both of) a `streamComplete` or `streamChat` function. Here is an example:
If you are using an LLM API that isn't already [supported by Continue](./model-providers.md), and is not an OpenAI-compatible API, you'll need to define a `CustomLLM` object in `config.ts`. This object only requires one of (or both of) a `streamComplete` or `streamChat` function. Here is an example:
```typescript title="~/.continue/config.ts"
export function modifyConfig(config: Config): Config {

View file

@ -1,12 +1,29 @@
---
title: Select providers
description: Configure LLM providers
keywords: [openai, anthropic, gemini, ollama, ggml]
title: Model Providers
description: Configure and integrate various LLM (Large Language Model) providers for chat, autocomplete, and embedding models, whether self-hosted, remote, or via SaaS.
keywords:
[
large language models,
LLM providers,
open-source LLM,
commercial LLM,
self-hosted LLM,
remote LLM,
SaaS LLM,
AI model configuration,
AI providers,
OpenAI,
Anthropic,
Gemini,
Ollama,
HuggingFace,
AWS Bedrock,
]
---
# Select providers
# Model Providers
Continue makes it easy to use different providers for serving your chat, autocomplete, and embeddings models.
Configure and integrate various LLM (Large Language Model) providers for chat, autocomplete, and embedding models, whether self-hosted, remote, or via SaaS.
To select the ones you want to use, add them to your `config.json`.

View file

@ -9,5 +9,5 @@ You will need to decide which models and providers you use for [chat](select-mod
Learn more:
- [Configuration](configuration.md)
- [Select providers](select-provider.md)
- [Model Providers](model-providers.md)
- [Select models](select-model.md)

View file

@ -87,4 +87,4 @@ We recommend the following embeddings models, which are used for codebase retrie
_You can also use other embeddings models by adding them to your `config.json`._
**In addition to selecting models, you will need to figure out [what providers to use](./select-provider.md).**
**In addition to selecting models, you will need to figure out [what model providers to use](./model-providers.md).**

View file

@ -185,6 +185,10 @@ const config = {
from: "/model-setup/configuration",
to: "/setup/configuration",
},
{
from: "/setup/select-provider",
to: "/setup/model-providers",
},
],
},
],

View file

@ -25,7 +25,7 @@ const sidebars = {
items: [
"setup/overview",
"setup/configuration",
"setup/select-provider",
"setup/model-providers",
"setup/select-model",
],
},

View file

@ -1395,6 +1395,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {
@ -1955,7 +1995,13 @@
"type": "object",
"properties": {
"name": {
"enum": ["cohere", "voyage", "llm", "free-trial", "huggingface-tei"]
"enum": [
"cohere",
"voyage",
"llm",
"free-trial",
"huggingface-tei"
]
},
"params": {
"type": "object"
@ -2070,7 +2116,7 @@
"default": false
},
"truncation_direction": {
"enum": ["Right","Left"],
"enum": ["Right", "Left"],
"markdownDescription": "Wether to truncate sequences from the `left` or `right`.",
"default": "Right"
}

@ -1 +0,0 @@
Subproject commit 4cf94d7023f5063f912d376027194fbd67670ba5

@ -1 +0,0 @@
Subproject commit 2eafdff54b1a77c6d403fa26a64c6793d7a4dfb9

@ -1 +0,0 @@
Subproject commit 9218fea4483ffcbbdf1471c83f65c01f3c25f554

@ -1 +0,0 @@
Subproject commit 2f0e7fbe962312a1b8bef8a29ed1ac4111ab11c4

View file

@ -1395,6 +1395,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {
@ -1955,7 +1995,13 @@
"type": "object",
"properties": {
"name": {
"enum": ["cohere", "voyage", "llm", "free-trial", "huggingface-tei"]
"enum": [
"cohere",
"voyage",
"llm",
"free-trial",
"huggingface-tei"
]
},
"params": {
"type": "object"
@ -2070,7 +2116,7 @@
"default": false
},
"truncation_direction": {
"enum": ["Right","Left"],
"enum": ["Right", "Left"],
"markdownDescription": "Wether to truncate sequences from the `left` or `right`.",
"default": "Right"
}

View file

@ -1395,6 +1395,46 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": ["docs"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": ["title", "startUrl"]
}
}
},
"required": ["sites"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {
@ -1955,7 +1995,13 @@
"type": "object",
"properties": {
"name": {
"enum": ["cohere", "voyage", "llm", "free-trial", "huggingface-tei"]
"enum": [
"cohere",
"voyage",
"llm",
"free-trial",
"huggingface-tei"
]
},
"params": {
"type": "object"
@ -2070,7 +2116,7 @@
"default": false
},
"truncation_direction": {
"enum": ["Right","Left"],
"enum": ["Right", "Left"],
"markdownDescription": "Wether to truncate sequences from the `left` or `right`.",
"default": "Right"
}

View file

@ -1541,6 +1541,55 @@
}
},
"allOf": [
{
"if": {
"properties": {
"name": {
"enum": [
"docs"
]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"sites": {
"type": "array",
"items": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"startUrl": {
"type": "string"
},
"rootUrl": {
"type": "string"
},
"maxDepth": {
"type": "integer"
}
},
"required": [
"title",
"startUrl"
]
}
}
},
"required": [
"sites"
]
}
},
"required": [
"params"
]
}
},
{
"if": {
"properties": {

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.185",
"version": "0.9.189",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.185",
"version": "0.9.189",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -97,7 +97,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@continuedev/config-types": "^1.0.8",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.186",
"version": "0.9.187",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -94,6 +94,16 @@
"default": false,
"markdownDescription": "Pause Continue's tab autocomplete feature when your battery is low."
},
"continue.pauseCodebaseIndexOnStart": {
"type": "boolean",
"default": false,
"markdownDescription": "Pause Continue's codebase index on start."
},
"continue.enableDebugLogs": {
"type": "boolean",
"default": false,
"markdownDescription": "Enable Continue Debug Logs in the Output panel."
},
"continue.remoteConfigServerUrl": {
"type": "string",
"default": null,

View file

@ -12,12 +12,55 @@ export class ContinueGUIWebviewViewProvider
public static readonly viewType = "continue.continueGUIView";
public webviewProtocol: VsCodeWebviewProtocol;
private updateDebugLogsStatus() {
const settings = vscode.workspace.getConfiguration("continue");
this.enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (this.enableDebugLogs) {
this.outputChannel.show(true);
} else {
this.outputChannel.hide();
}
}
// Show or hide the output channel on enableDebugLogs
private setupDebugLogsListener() {
vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration('continue.enableDebugLogs')) {
const settings = vscode.workspace.getConfiguration("continue");
const enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (enableDebugLogs) {
this.outputChannel.show(true);
} else {
this.outputChannel.hide();
}
}
});
}
private async handleWebviewMessage(message: any) {
if (message.messageType === "log") {
const settings = vscode.workspace.getConfiguration("continue");
const enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (message.level === "debug" && !enableDebugLogs) {
return; // Skip debug logs if enableDebugLogs is false
}
const timestamp = new Date().toISOString().split(".")[0];
const logMessage = `[${timestamp}] [${message.level.toUpperCase()}] ${message.text}`;
this.outputChannel.appendLine(logMessage);
}
}
resolveWebviewView(
webviewView: vscode.WebviewView,
_context: vscode.WebviewViewResolveContext,
_token: vscode.CancellationToken,
): void | Thenable<void> {
this._webview = webviewView.webview;
this._webview.onDidReceiveMessage((message) =>
this.handleWebviewMessage(message),
);
webviewView.webview.html = this.getSidebarContent(
this.extensionContext,
webviewView,
@ -26,6 +69,8 @@ export class ContinueGUIWebviewViewProvider
private _webview?: vscode.Webview;
private _webviewView?: vscode.WebviewView;
private outputChannel: vscode.OutputChannel;
private enableDebugLogs: boolean;
get isVisible() {
return this._webviewView?.visible;
@ -50,11 +95,17 @@ export class ContinueGUIWebviewViewProvider
});
}
constructor(
private readonly configHandlerPromise: Promise<ConfigHandler>,
private readonly windowId: string,
private readonly extensionContext: vscode.ExtensionContext,
) {
this.outputChannel = vscode.window.createOutputChannel("Continue");
this.enableDebugLogs = false;
this.updateDebugLogsStatus();
this.setupDebugLogsListener();
this.webviewProtocol = new VsCodeWebviewProtocol(
(async () => {
const configHandler = await this.configHandlerPromise;
@ -131,6 +182,22 @@ export class ContinueGUIWebviewViewProvider
<body>
<div id="root"></div>
${`<script>
function log(level, ...args) {
const text = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ');
vscode.postMessage({ messageType: 'log', level, text, messageId: "log" });
}
window.console.log = (...args) => log('log', ...args);
window.console.info = (...args) => log('info', ...args);
window.console.warn = (...args) => log('warn', ...args);
window.console.error = (...args) => log('error', ...args);
window.console.debug = (...args) => log('debug', ...args);
console.debug('Logging initialized');
</script>`}
${
inDevelopmentMode
? `<script type="module">

View file

@ -221,7 +221,7 @@ export class VsCodeExtension {
this.configHandler.reloadConfig();
});
vscode.workspace.onDidSaveTextDocument((event) => {
vscode.workspace.onDidSaveTextDocument(async (event) => {
// Listen for file changes in the workspace
const filepath = event.uri.fsPath;
@ -254,15 +254,18 @@ export class VsCodeExtension {
) {
// Update embeddings! (TODO)
}
// Reindex the workspaces
this.core.invoke("index/forceReIndex", undefined);
});
// When GitHub sign-in status changes, reload config
vscode.authentication.onDidChangeSessions((e) => {
vscode.authentication.onDidChangeSessions(async (e) => {
if (e.provider.id === "github") {
this.configHandler.reloadConfig();
} else if (e.provider.id === "continue") {
const sessionInfo = await getControlPlaneSessionInfo(true);
this.webviewProtocolPromise.then(async (webviewProtocol) => {
const sessionInfo = await getControlPlaneSessionInfo(true);
webviewProtocol.request("didChangeControlPlaneSessionInfo", {
sessionInfo,
});
@ -270,6 +273,7 @@ export class VsCodeExtension {
// To make sure continue-proxy models and anything else requiring it get updated access token
this.configHandler.reloadConfig();
});
this.core.invoke("didChangeControlPlaneSessionInfo", { sessionInfo });
}
});

View file

@ -522,6 +522,8 @@ class VsCodeIde implements IDE {
),
userToken: settings.get<string>("userToken", ""),
enableControlServerBeta: internalBetaPathExists(),
pauseCodebaseIndexOnStart: settings.get<boolean>("pauseCodebaseIndexOnStart", false),
enableDebugLogs: settings.get<boolean>("enableDebugLogs", false),
// settings.get<boolean>(
// "enableControlServerBeta",
// false,

2
gui/package-lock.json generated
View file

@ -90,7 +90,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@continuedev/config-types": "^1.0.8",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",

View file

@ -0,0 +1,22 @@
export default function Logo({
height,
width,
}: {
height: number;
width: number;
}) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={width}
height={height}
viewBox="0 0 24 24"
fill="none"
>
<path
d="M20.5286 3.26811L19.1512 5.65694L22.6328 11.6849C22.6582 11.7306 22.6735 11.7866 22.6735 11.8374C22.6735 11.8882 22.6582 11.9441 22.6328 11.9899L19.1512 18.0229L20.5286 20.4117L25.4791 11.8374L20.5286 3.26303V3.26811ZM18.6176 5.3469L19.995 2.95807H17.2402L15.8628 5.3469H18.6227H18.6176ZM15.8577 5.96697L19.075 11.5324H21.8298L18.6176 5.96697H15.8577ZM18.6176 17.7179L21.8298 12.1474H19.075L15.8577 17.7179H18.6176ZM15.8577 18.338L17.2351 20.7167H19.9899L18.6125 18.338H15.8526H15.8577ZM6.52098 21.3063C6.46507 21.3063 6.41424 21.291 6.3685 21.2656C6.32276 21.2402 6.28209 21.1995 6.25668 21.1538L2.77002 15.1207H0.0152482L4.9657 23.69H14.8615L13.4841 21.3063H6.52606H6.52098ZM14.0178 20.9962L15.3952 23.38L16.7726 20.9911L15.3952 18.6023L14.0178 20.9911V20.9962ZM14.8615 18.2974H8.43712L7.05973 20.6862H13.4841L14.8615 18.2974ZM7.89836 17.9924L4.68108 12.4219L3.30369 14.8107L6.52098 20.3812L7.89836 17.9924ZM0.0101654 14.5007H2.76494L4.14232 12.1118H1.39263L0.0101654 14.5007ZM6.24143 2.5413C6.26685 2.49556 6.30751 2.4549 6.35325 2.42948C6.399 2.40407 6.4549 2.38882 6.50573 2.38882H13.474L14.8514 0H4.95045L0 8.57435H2.75477L6.23127 2.54638L6.24143 2.5413ZM4.14232 11.5782L2.76494 9.18934H0.0101654L1.38755 11.5782H4.14232ZM6.51081 3.31386L3.29861 8.8793L4.67599 11.2681L7.8882 5.70268L6.51081 3.31386ZM13.4791 3.00382H7.04448L8.42187 5.39264H14.8564L13.4791 3.00382ZM15.3952 5.0826L16.7675 2.69886L15.3952 0.310038L14.0178 2.69378L15.3952 5.0826Z"
fill="currentColor"
></path>
</svg>
);
}

View file

@ -160,58 +160,62 @@ function ProfileSwitcher(props: {}) {
return (
<>
{controlServerBetaEnabled && profiles.length > 0 && (
<StyledListbox
value={"GPT-4"}
onChange={(id: string) => {
ideMessenger.request("didChangeSelectedProfile", { id });
}}
>
<div className="relative">
<StyledListboxButton>
<div>{selectedProfile()?.title}</div>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon
className="h-4 w-4 text-gray-400"
aria-hidden="true"
/>
</div>
</StyledListboxButton>
{topDiv &&
ReactDOM.createPortal(
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<StyledListboxOptions>
{profiles.map((option, idx) => (
<ListBoxOption
selected={option.id === selectedProfileId}
option={option}
idx={idx}
key={idx}
showDelete={profiles.length > 1}
/>
))}
<div
className="px-2 py-1"
style={{ color: lightGray, fontSize: getFontSize() - 2 }}
>
{profiles.length === 0 ? (
<i>No profiles found</i>
) : (
"Select profile"
)}
</div>
</StyledListboxOptions>
</Transition>,
topDiv,
)}
</div>
</StyledListbox>
)}
{controlServerBetaEnabled &&
profiles.some((profile) => profile.id !== "local") && (
<StyledListbox
value={"GPT-4"}
onChange={(id: string) => {
ideMessenger.request("didChangeSelectedProfile", { id });
}}
>
<div className="relative">
<StyledListboxButton>
<div>{selectedProfile()?.title}</div>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon
className="h-4 w-4 text-gray-400"
aria-hidden="true"
/>
</div>
</StyledListboxButton>
{topDiv &&
ReactDOM.createPortal(
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<StyledListboxOptions>
{profiles.map((option, idx) => (
<ListBoxOption
selected={option.id === selectedProfileId}
option={option}
idx={idx}
key={idx}
showDelete={profiles.length > 1}
/>
))}
<div
className="px-2 py-1"
style={{
color: lightGray,
fontSize: getFontSize() - 2,
}}
>
{profiles.length === 0 ? (
<i>No workspaces found</i>
) : (
"Select workspace"
)}
</div>
</StyledListboxOptions>
</Transition>,
topDiv,
)}
</div>
</StyledListbox>
)}
{/* Settings button (either opens config.json or /settings page in control plane) */}
<HeaderButtonWithText

View file

@ -41,6 +41,7 @@ function AddDocsDialog() {
rootUrl: docsUrl,
title: docsTitle,
maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth,
faviconUrl: new URL("/favicon.ico", docsUrl).toString(),
};
ideMessenger.post("context/addDocs", siteIndexingConfig);

View file

@ -3,6 +3,7 @@ import {
BarsArrowDownIcon,
HandThumbDownIcon,
HandThumbUpIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { stripImages } from "core/llm/countTokens";
@ -34,6 +35,7 @@ interface StepContainerProps {
isFirst: boolean;
isLast: boolean;
index: number;
subtext?: string;
}
// #region styled components
@ -58,7 +60,7 @@ const ContentDiv = styled.div<{ isUserInput: boolean; fontSize?: number }>`
background-color: ${(props) =>
props.isUserInput ? vscInputBackground : vscBackground};
font-size: ${(props) => props.fontSize || getFontSize()}px;
border-radius: ${defaultBorderRadius};
// border-radius: ${defaultBorderRadius};
overflow: hidden;
`;
@ -138,75 +140,92 @@ function StepContainer(props: StepContainerProps) {
/>
)}
</ContentDiv>
<div className="h-2"></div>
{(isHovered || typeof feedback !== "undefined") && !active && (
<div
className="flex items-center gap-2 right-2 absolute -bottom-1"
className="flex items-center justify-between absolute -bottom-2 w-full"
style={{ zIndex: 200 }}
>
{truncatedEarly && (
<div
className="pl-2"
style={{ color: lightGray, fontSize: getFontSize() - 3 }}
>
{props.subtext ?? ""}
</div>
<div className="flex items-center gap-2 pr-2">
{truncatedEarly && (
<HeaderButtonWithText
text="Continue generation"
onClick={(e) => {
props.onContinueGeneration();
}}
>
<BarsArrowDownIcon
color={lightGray}
width="1.2em"
height="1.2em"
/>
</HeaderButtonWithText>
)}
<CopyButton
text={stripImages(props.item.message.content)}
color={lightGray}
/>
<HeaderButtonWithText
text="Continue generation"
text="Regenerate"
onClick={(e) => {
props.onContinueGeneration();
props.onRetry();
}}
>
<BarsArrowDownIcon
<ArrowUturnLeftIcon
color={lightGray}
width="1.2em"
height="1.2em"
/>
</HeaderButtonWithText>
)}
<CopyButton
text={stripImages(props.item.message.content)}
color={lightGray}
/>
<HeaderButtonWithText
text="Regenerate"
onClick={(e) => {
props.onRetry();
}}
>
<ArrowUturnLeftIcon
color={lightGray}
width="1.2em"
height="1.2em"
/>
</HeaderButtonWithText>
{feedback === false || (
<HeaderButtonWithText text="Helpful">
<HandThumbUpIcon
className={
"cursor-pointer hover:text-green-500" +
(feedback === true ? " text-green-500" : "")
}
{feedback === false || (
<HeaderButtonWithText text="Helpful">
<HandThumbUpIcon
className={
"cursor-pointer hover:text-green-500" +
(feedback === true ? " text-green-500" : "")
}
width="1.2em"
height="1.2em"
color={lightGray}
onClick={() => {
sendFeedback(true);
}}
/>
</HeaderButtonWithText>
)}
{feedback === true || (
<HeaderButtonWithText text="Unhelpful">
<HandThumbDownIcon
className={
"cursor-pointer hover:text-red-500" +
(feedback === false ? " text-red-500" : "")
}
width="1.2em"
height="1.2em"
color={lightGray}
onClick={() => {
sendFeedback(false);
}}
/>
</HeaderButtonWithText>
)}
<HeaderButtonWithText text="Delete Message">
<TrashIcon
color={lightGray}
width="1.2em"
height="1.2em"
color={lightGray}
onClick={() => {
sendFeedback(true);
props.onDelete();
}}
/>
</HeaderButtonWithText>
)}
{feedback === true || (
<HeaderButtonWithText text="Unhelpful">
<HandThumbDownIcon
className={
"cursor-pointer hover:text-red-500" +
(feedback === false ? " text-red-500" : "")
}
width="1.2em"
height="1.2em"
color={lightGray}
onClick={() => {
sendFeedback(false);
}}
/>
</HeaderButtonWithText>
)}
</div>
</div>
)}
</div>

View file

@ -98,7 +98,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
style={{ color: lightGray }}
></ChevronDownIcon>
)}
Context Used
<span className="ms-1">Context Used</span>
</div>
{open && (
<div

View file

@ -23,27 +23,19 @@ import {
} from "../../util";
import ModelSelect from "../modelSelection/ModelSelect";
const paddingTop = 4;
const height = 20;
const StyledDiv = styled.div<{ hidden?: boolean }>`
const StyledDiv = styled.div<{ isHidden: boolean }>`
display: flex;
justify-content: space-between;
flex-wrap: wrap-reverse;
flex-direction: row-reverse;
gap: 1px;
background-color: ${vscInputBackground};
padding-top: ${paddingTop}px;
height: ${height}px;
${(props) => (props.hidden ? "display: none;" : "")}
align-items: center;
z-index: 50;
font-size: ${getFontSize() - 4}px;
cursor: text;
cursor: ${props => props.isHidden ? 'default' : 'text'};
opacity: ${props => props.isHidden ? 0 : 1};
pointer-events: ${props => props.isHidden ? 'none' : 'auto'};
& > * {
flex: 0 0 auto;
@ -90,11 +82,8 @@ function InputToolbar(props: InputToolbarProps) {
return (
<>
{props.hidden && (
<div style={{ height: `${height + paddingTop}px` }}></div>
)}
<StyledDiv
hidden={props.hidden}
isHidden={props.hidden}
onClick={props.onClick}
id="input-toolbar"
>
@ -136,11 +125,6 @@ function InputToolbar(props: InputToolbarProps) {
)}
<EnterButton
offFocus={props.usingCodebase}
// disabled={
// !active &&
// (!(inputRef.current as any)?.value ||
// typeof client === "undefined")
// }
onClick={(e) => {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e),

View file

@ -53,6 +53,7 @@ import {
getSlashCommandDropdownOptions,
} from "./getSuggestion";
import { ComboBoxItem } from "./types";
import { usePostHog } from "posthog-js/react";
const InputBoxDiv = styled.div`
resize: none;
@ -80,7 +81,8 @@ const InputBoxDiv = styled.div`
color: ${lightGray}cc;
}
position: relative;
display: flex;
flex-direction: column;
`;
const HoverDiv = styled.div`
@ -152,6 +154,8 @@ function TipTapEditor(props: TipTapEditorProps) {
const { saveSession } = useHistory(dispatch);
const posthog = usePostHog();
const inSubmenuRef = useRef<string | undefined>(undefined);
const inDropdownRef = useRef(false);
@ -285,10 +289,13 @@ function TipTapEditor(props: TipTapEditorProps) {
return true;
},
"Alt-Enter": () => {
posthog.capture("gui_use_active_file_enter");
onEnterRef.current({
useCodebase: false,
noContext: useActiveFile,
});
return true;
},
"Cmd-Backspace": () => {

View file

@ -99,40 +99,19 @@ async function resolveEditorContent(
let contextItemsText = "";
let contextItems: ContextItemWithId[] = [];
for (const item of contextItemAttrs) {
if (item.itemType === "file") {
// This is a quick way to resolve @file references
const basename = getBasename(item.id);
const relativeFilePath = getRelativePath(
item.id,
await ideMessenger.ide.getWorkspaceDirs(),
);
const rawContent = await ideMessenger.ide.readFile(item.id);
const content = `\`\`\`${relativeFilePath}\n${rawContent}\n\`\`\`\n`;
contextItemsText += content;
contextItems.push({
name: basename,
description: item.id,
content,
id: {
providerTitle: "file",
itemId: item.id,
},
});
} else {
const data = {
name: item.itemType === "contextProvider" ? item.id : item.itemType,
query: item.query,
fullInput: stripImages(parts),
selectedCode,
};
const resolvedItems = await ideMessenger.request(
"context/getContextItems",
data,
);
contextItems.push(...resolvedItems);
for (const resolvedItem of resolvedItems) {
contextItemsText += resolvedItem.content + "\n\n";
}
const data = {
name: item.itemType === "contextProvider" ? item.id : item.itemType,
query: item.query,
fullInput: stripImages(parts),
selectedCode,
};
const resolvedItems = await ideMessenger.request(
"context/getContextItems",
data,
);
contextItems.push(...resolvedItems);
for (const resolvedItem of resolvedItems) {
contextItemsText += resolvedItem.content + "\n\n";
}
}

View file

@ -6,7 +6,7 @@ import {
groupByLastNPathParts,
} from "core/util";
import MiniSearch, { SearchResult } from "minisearch";
import { useContext, useEffect, useState } from "react";
import { useContext, useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { selectContextProviderDescriptions } from "../redux/selectors";
@ -107,6 +107,90 @@ function useSubmenuContextProviders() {
};
}, []);
const getSubmenuSearchResults = useMemo(
() =>
(providerTitle: string | undefined, query: string): SearchResult[] => {
console.debug(
"Executing getSubmenuSearchResults. Provider:",
providerTitle,
"Query:",
query,
);
console.debug("Current minisearches:", Object.keys(minisearches));
if (providerTitle === undefined) {
// Return search combined from all providers
const results = Object.keys(minisearches).map((providerTitle) => {
const results = minisearches[providerTitle].search(
query,
MINISEARCH_OPTIONS,
);
console.debug(`Search results for ${providerTitle}:`, results.length);
return results.map((result) => {
return { ...result, providerTitle };
});
});
return results.flat().sort((a, b) => b.score - a.score);
}
if (!minisearches[providerTitle]) {
console.debug(`No minisearch found for provider: ${providerTitle}`);
return [];
}
const results = minisearches[providerTitle]
.search(query, MINISEARCH_OPTIONS)
.map((result) => {
return { ...result, providerTitle };
});
console.debug(`Search results for ${providerTitle}:`, results.length);
return results;
},
[minisearches],
);
const getSubmenuContextItems = useMemo(
() =>
(
providerTitle: string | undefined,
query: string,
limit: number = MAX_LENGTH,
): (ContextSubmenuItem & { providerTitle: string })[] => {
console.debug(
"Executing getSubmenuContextItems. Provider:",
providerTitle,
"Query:",
query,
"Limit:",
limit,
);
const results = getSubmenuSearchResults(providerTitle, query);
if (results.length === 0) {
const fallbackItems = (fallbackResults[providerTitle] ?? [])
.slice(0, limit)
.map((result) => {
return {
...result,
providerTitle,
};
});
console.debug("Using fallback results:", fallbackItems.length);
return fallbackItems;
}
const limitedResults = results.slice(0, limit).map((result) => {
return {
id: result.id,
title: result.title,
description: result.description,
providerTitle: result.providerTitle,
};
});
return limitedResults;
},
[fallbackResults, getSubmenuSearchResults],
);
useEffect(() => {
if (contextProviderDescriptions.length === 0 || loaded) {
return;
@ -141,61 +225,6 @@ function useSubmenuContextProviders() {
});
}, [contextProviderDescriptions, loaded]);
function getSubmenuSearchResults(
providerTitle: string | undefined,
query: string,
): SearchResult[] {
if (providerTitle === undefined) {
// Return search combined from all providers
const results = Object.keys(minisearches).map((providerTitle) => {
const results = minisearches[providerTitle].search(
query,
MINISEARCH_OPTIONS,
);
return results.map((result) => {
return { ...result, providerTitle };
});
});
return results.flat().sort((a, b) => b.score - a.score);
}
if (!minisearches[providerTitle]) {
return [];
}
return minisearches[providerTitle]
.search(query, MINISEARCH_OPTIONS)
.map((result) => {
return { ...result, providerTitle };
});
}
function getSubmenuContextItems(
providerTitle: string | undefined,
query: string,
limit: number = MAX_LENGTH,
): (ContextSubmenuItem & { providerTitle: string })[] {
const results = getSubmenuSearchResults(providerTitle, query);
if (results.length === 0) {
return (fallbackResults[providerTitle] ?? [])
.slice(0, limit)
.map((result) => {
return {
...result,
providerTitle,
};
});
}
return results.slice(0, limit).map((result) => {
return {
id: result.id,
title: result.title,
description: result.description,
providerTitle: result.providerTitle,
};
});
}
return {
getSubmenuContextItems,
addItem,

View file

@ -39,6 +39,7 @@ import { useWebviewListener } from "../hooks/useWebviewListener";
import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import {
clearLastResponse,
deleteMessage,
newSession,
setInactive,
} from "../redux/slices/stateSlice";
@ -103,6 +104,13 @@ const StepsDiv = styled.div`
// z-index: 0;
// bottom: 12px;
// }
.thread-message {
margin: 16px 8px 0 8px;
}
.thread-message:not(:first-child) {
border-top: 1px solid ${lightGray}22;
}
`;
const NewSessionButton = styled.div`
@ -125,6 +133,38 @@ const NewSessionButton = styled.div`
cursor: pointer;
`;
const ThreadHead = styled.div`
display: flex;
align-items: center;
gap: 6px;
margin: 18px 6px 0 6px;
`;
const THREAD_AVATAR_SIZE = 15;
const ThreadAvatar = styled.div`
width: 24px;
height: 24px;
border-radius: 50%;
background-color: rgba(248, 248, 248, 0.75);
color: #000;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(136, 136, 136, 0.3);
`;
const ThreadUserTitle = styled.div`
text-transform: capitalize;
font-weight: 500;
margin-bottom: 2px;
`;
const ThreadUserName = styled.div`
font-size: ${getFontSize() - 3}px;
color: ${lightGray};
`;
function fallbackRender({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
@ -374,70 +414,81 @@ function GUI() {
contextItems={item.contextItems}
></ContinueInputBox>
) : (
<TimelineItem
item={item}
iconElement={
false ? (
<CodeBracketSquareIcon width="16px" height="16px" />
) : false ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon
width="16px"
height="16px"
/>
)
}
open={
typeof stepsOpen[index] === "undefined"
? false
? false
: true
: stepsOpen[index]!
}
onToggle={() => {}}
>
<StepContainer
index={index}
isLast={index === sessionState.history.length - 1}
isFirst={index === 0}
<div className="thread-message">
<TimelineItem
item={item}
iconElement={
false ? (
<CodeBracketSquareIcon
width="16px"
height="16px"
/>
) : false ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon
width="16px"
height="16px"
/>
)
}
open={
typeof stepsOpen[index] === "undefined"
? true
? false
? false
: true
: stepsOpen[index]!
}
key={index}
onUserInput={(input: string) => {}}
item={item}
onReverse={() => {}}
onRetry={() => {
streamResponse(
state.history[index - 1].editorState,
state.history[index - 1].modifiers ??
defaultInputModifiers,
ideMessenger,
index - 1,
);
}}
onContinueGeneration={() => {
window.postMessage(
{
messageType: "userInput",
data: {
input:
"Continue your response exactly where you left off:",
onToggle={() => {}}
>
<StepContainer
index={index}
isLast={index === sessionState.history.length - 1}
isFirst={index === 0}
open={
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
key={index}
onUserInput={(input: string) => {}}
item={item}
onReverse={() => {}}
onRetry={() => {
streamResponse(
state.history[index - 1].editorState,
state.history[index - 1].modifiers ??
defaultInputModifiers,
ideMessenger,
index - 1,
);
}}
onContinueGeneration={() => {
window.postMessage(
{
messageType: "userInput",
data: {
input:
"Continue your response exactly where you left off:",
},
},
},
"*",
);
}}
onDelete={() => {}}
/>
</TimelineItem>
"*",
);
}}
onDelete={() => {
dispatch(deleteMessage(index));
}}
subtext={
item.promptLogs?.[0]?.completionOptions?.model ??
""
}
/>
</TimelineItem>
</div>
)}
</ErrorBoundary>
</Fragment>

View file

@ -244,6 +244,23 @@ export const stateSlice = createSlice({
// state.contextItems = [];
state.active = true;
},
deleteMessage: (state, action: PayloadAction<number>) => {
const index = action.payload + 1;
if (index >= 0 && index < state.history.length) {
// Delete the current message
state.history.splice(index, 1);
// If the next message is an assistant message, delete it too
if (
index < state.history.length &&
state.history[index].message.role === "assistant"
) {
state.history.splice(index, 1);
}
}
},
initNewActiveMessage: (
state,
{
@ -500,5 +517,6 @@ export const {
clearLastResponse,
consumeMainEditorContent,
setSelectedProfileId,
deleteMessage,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-types",
"version": "1.0.7",
"version": "1.0.8",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

File diff suppressed because it is too large Load diff

View file

@ -176,6 +176,15 @@ export const rerankerSchema = z.object({
export type Reranker = z.infer<typeof rerankerSchema>;
export const analyticsSchema = z.object({
provider: z.enum([
"posthog",
"amplitude",
"segment",
"elastic",
"mixpanel",
"splunk",
"datadog",
]),
url: z.string().optional(),
clientKey: z.string().optional(),
});