Compare commits

..

581 Commits

Author SHA1 Message Date
Jason Hawk Harris
cff1669bc1
Svelte: Perforce UI elements refactor (#64279)
## UI Updates for Perforce Depots and Git Repos

Fixes SRCH-530

**NOTE: This PR is a refactor of an earlier
[PR](https://github.com/sourcegraph/sourcegraph/pull/64014) that was
reverted. For that reason, the PR description is largely the same.**

This PR introduces changes to the UI to differentiate between Perforce
Depots and Git repositories. Below are the key changes included in this
commit:

### 1. Dynamic Top-Level Navigation

**For Perforce Depots:**

![Screenshot 2024-07-31 at 10 10 37
AM](https://github.com/user-attachments/assets/2d261b51-f8fa-4599-acae-3520d38996f3)

**For Git Repos:**

![Screenshot 2024-07-31 at 10 10 14
AM](https://github.com/user-attachments/assets/0f9ee3f7-918a-42d8-908f-04593ed52ebd)

### 2. Tabs on Revision Picker

**For Perforce Depots:**

Since we only need one tab for changelists, no tabs are shown.

![Screenshot 2024-07-31 at 10 20 24
AM](https://github.com/user-attachments/assets/f1006d56-67aa-41ab-a13b-905e157cb283)

**For Git Repos:**

We have tabs for Branches, Tags, and Commits.

![Screenshot 2024-07-31 at 10 23 02
AM](https://github.com/user-attachments/assets/38907d51-0407-4cd7-ad4c-1c5967dfddf3)

### 3. Commits/Changelists Page

**For Git Repos:**

The page displays Git commits.

![Screenshot 2024-07-31 at 10 26 23
AM](https://github.com/user-attachments/assets/85245d1d-708f-4d51-9da3-0425c3f085d0)

**For Perforce Depots:**

The page displays Perforce changelists.

![Screenshot 2024-07-31 at 10 26 39
AM](https://github.com/user-attachments/assets/2f6f16aa-d498-4763-949d-d1a13f9a26ac)

### 4. Vocabulary Adjustments

- We display either Git commit SHAs or Changelist IDs based on the
project type.
- For authorship, we use "submitted by" for Perforce and "committed by"
for Git.
- We refer to "Commits" for Git projects and "Changelists" for Perforce
projects.

**Examples:**

- **For Git Commits:**

![Screenshot 2024-07-31 at 10 37 08
AM](https://github.com/user-attachments/assets/ac15b0b3-4c85-4a4c-80c0-ec9384b72eca)

- **For Perforce Changelists:**

![Screenshot 2024-07-31 at 10 37 35
AM](https://github.com/user-attachments/assets/4230cb32-5285-4141-b374-f3ea23042e1d)

### 5. URL Mapping

URLs are now structured differently based on the project type:

- **Commits Page:**
  - Git: `/[repo-name]/-/commits`
  - Perforce: `/[repo-name]/-/changelists`
  
- **Individual Item Page:**
  - Git: `/[repo-name]/-/commit/[commit-hash]`
  - Perforce: `/[depot-name]/-/changelist/[changelist-ID]`

When viewing a specific commit or changelist:
- **Git:** `/[repo-name]@[git-commit-hash]`
- **Perforce:** `/[repo-name]@changelist/[changelist-id]`

_NOTE: The value displayed in the search field will also change
accordingly._


### What is left to be done?
**On repo search results, when searching a revision, we still show the
git commit SHA instead of the changelist ID for perforce depots:**
![Screenshot 2024-07-31 at 10 59 12
AM](https://github.com/user-attachments/assets/38bc2a3e-be8b-4585-9fe0-776149a7f230)

I plan to make a follow-up issue for this and begin work on it
immediately. It's a little trickier than the other changes because in
the RepositoryMatch type, there is no value that can help us determine
whether a project is a depot or a repo. We need to find another way to
fetch that data.

### Request for reviewers: 
1. Please try to break these new features and tell me what you find. I
stumbled on a number of little gotchas while working on this, and I'm
sure I've missed some.

## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
- Manual/Visual testing
- Adjust e2e and integration tests to obtain a passing CI
- Test directly visiting a URL versus getting there via click
- Add unit tests for new/updated helper functions

---------

Co-authored-by: Camden Cheek <camden@ccheek.com>
2024-08-14 19:18:24 +00:00
Varun Gandhi
f403bfc1ff
chore: Bump autoindexing image SHAs (#64472) 2024-08-14 16:39:08 +00:00
Jean-Hadrien Chabran
1c3ba6eb85
chore(ci): lower concurrent jobs when pushing to dockerhub (#64469)
We're currently evaluating only pushing on Dockerhub when releasing, as
everything else uses GCR, but until then, we lower the concurrency to 4
when pushing there, and we keep 8 on the others.

Follow-up to https://github.com/sourcegraph/devx-support/issues/1163

## Test plan

CI
2024-08-14 16:23:39 +00:00
Robert Lin
6e828b0a14
feat/dotcom: use Enterprise Portal for all subscriptions UI (#64115)
Overview Loom:

1.
https://www.loom.com/share/988465de1c3a4caaa08fc6b22ffb74e5?sid=860f28cd-4dfb-4758-9bd9-d2f485ceb317
2. Announcement:
https://www.loom.com/share/8560388e0a4a404caf67d908820ed0d0?sid=6482815f-ac60-4251-95cc-307f527a60dd

tl;dr


![image](https://github.com/user-attachments/assets/542c5b64-5729-4a6a-91b2-e0373abb35fa)

![image](https://github.com/user-attachments/assets/9cc41a80-2ff1-4845-a290-823df242cd2e)

![image](https://github.com/user-attachments/assets/47c9a400-d091-416f-a85c-f1dcc93d880d)

TODO:

- [x] Fix the "edit instance type" input
- [x] ~Subscription view: reload on changing the Enterprise Portal
environment selector~ ->
https://linear.app/sourcegraph/issue/CORE-245/dotcom-subscriptions-ui-enterprise-portal-instance-selector-doesnt,
use a jank reload for now
- [x] CI

Closes
https://linear.app/sourcegraph/issue/CORE-100/enterprise-portal-migrate-away-from-dotcom-db-as-source-of-truth

## Test plan

Manual testing for UI via `sg start dotcom` ->
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions

The PRs this PR is stacked on top of implement testing of the backend
capabilities
2024-08-14 15:32:22 +00:00
Robert Lin
fef7af964b
Revert "chore(local): dont buffer sg updatecheck commencement notice … (#64456)
…(#64329)"

This reverts commit c4fefc1fe6.

See thread
https://sourcegraph.slack.com/archives/C04MYFW01NV/p1723219276178049:
I'm consistently getting strange output after #64329, and building `sg`
from before that change seems to not have this problem.

## Test plan

```
go build -o ./sg ./dev/sg && ./sg install -f -p=false
SKIP_AUTO_UPDATE=false sg -skip-auto-update=false msp fleet
```

Output looks normal.

But then, reverting back to main:
```
sg update
sg msp fleet
```

Some odd character sequences show up as described in
https://sourcegraph.slack.com/archives/C04MYFW01NV/p1723219276178049
2024-08-14 08:04:02 -07:00
Keegan Carruthers-Smith
9981c14e40
migrations: avoid duplicate foreign key constraints when tenant_id re-run (#64465)
ALTER TABLE with a foreign key constraint will _always_ add the
constraint, which means we always require a table lock even if this
migration has run. So we check if the column exists first.

The motivation for this change was me noticing slow migrations against
S2, even though it had been migrated already. This speeds it up since it
avoids a bunch of locks.

In testing I kept running into issues with the lsif_* tables. We agreed
we will only migrate them later.

Test Plan: ran against my local instance and S2 multiple times and CI.
Also manually ran the down and up migration against dotcom
2024-08-14 16:57:32 +02:00
Julie Tibshirani
70e98dbcbd
Redis: expose KeyValue.WithPrefix (#64466)
This PR makes `WithPrefix` visible on the `KeyValue` interface.
Previously, we had other interface implementations that did not support
`WithPrefix`, but now `redisKeyValue` is the only implementation.
`WithPrefix` is currently just used in tests, but it's broadly useful
and will help clean up a bunch of places that wrap Redis and manually
add key prefixes.
2024-08-14 17:41:59 +03:00
Keegan Carruthers-Smith
3268ade126
migrations: commit between table locks and use when condition for triggers (#64462)
The improvement to the triggers I tried to ship yesterday failed on
dotcom. This is because it has the same issue as the tenant_id column
where we can't acquire the ShareRowExclusiveLock for multiple important
tables in a transaction without deadlocking. We use the same technique
where we commit and restart the transaction. This is safe to do since
even if it fails, the migration is idempotent and partial migration
still works.

Additionally after reading the documentation on triggers more deeply
[1], I noticed we can add in a WHEN clause to triggers. We already have
this in the functions, but this should be more efficient.

I didn't want to remove the condition from the functions just yet, since
that makes the migration more risky under partial failure.

## Test Plan

CI. Also added BEGIN and COMMIT to the migration than ran locally with

``` shell
psql -f migrations/frontend/1723557836_faster_soft_delete_trigger_for_permissions/up.sql
```


Then inspected the DB state for repo and had a good looking trigger come
back

```
\d+ repo
...snip
Triggers:
  trig_delete_user_repo_permissions_on_repo_soft_delete AFTER UPDATE
  OF deleted_at ON repo FOR EACH ROW WHEN (new.deleted_at IS NOT NULL
  AND old.deleted_at IS NULL) EXECUTE FUNCTION
  delete_user_repo_permissions_on_repo_soft_delete()
```

Additionally before landing I am going to manually run this migration on
S2 first, then on dotcom to see how it behaves when there is lots of
traffic and scale.
2024-08-14 15:38:35 +02:00
Qais Patankar
44f07c3966
Invalidate sessions on user deletion (#64445)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

When a user is deleted and then undeleted, the original web sessions
prior to the deletion are able to be reused. This is inconsistent with
the behaviour for access tokens: access tokens are revoked on user
deletion, but web sessions are not.

This makes it so that deleting the user account also forces a sign out
for that account.

It does this by setting `invalidated_sessions_at=now()`, which is
exactly the same thing that `InvalidateSessionsByIDs` does:


cbd12608b5/internal/database/users.go (L1040-L1045)

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

This change should be covered by the below existing test:
cbd12608b5/internal/database/users_test.go (L741)

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

* Deleting a user will now invalidate their web sessions
2024-08-14 12:00:10 +01:00
Erik Seliger
0aeb6fd0a0
tenant: Add test to verify that we don't regress on tables without tenant (#64368)
This test ensures that newly added tables also have the tenant_id
column. We will later extend this test to also check that RLS policies
exist, once we created them.

Test plan: Test passes, when I modify the new migration that adds
tenant_id everywhere to skip a table it fails with a nice error message.
2024-08-14 10:58:59 +00:00
Ólafur Páll Geirsson
1b1229c867
feat/API: implement /models and /models/{modelId} using TypeSpec (#64421)
Fixes CODY-3085
Fixes CODY-3086

Previously, there was no way for OpenAI clients to list the available
models on Sourcegraph or query metadata about a given model ID ("model
ref" using our internal terminology). This PR fixes that problem AND
additionally adds infrastructure to auto-generate Go models from a
TypeSpec specification.

[TypeSpec](https://typespec.io/) is an IDL to document REST APIs,
created by Microsoft. Historically, the Go code in this repository has
been the single source of truth about what exact JSON structures are
expected in HTTP request/response pairs in our REST endpoints. This new
TypeSpec infrastructure allows us to document these shapes at a higher
abstraction level, which has several benefits including automatic
OpenAPI generation, which we can use to generate docs on
sourcegraph.com/docs or automatically generate client bindings in
TypeScript (among many other use-cases).

I am planning to write an RFC to propose we start using TypeSpec for new
REST endpoints going forward. If the RFC is not approved then we can
just delete the new `tools/typespec_codegen` directory and keep the
generated code in the repo. It won't be a big difference in the end
compared our current manual approach of writing Go structs for HTTP
APIs.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
See test cases. I additionally wrote a basic python script with the
official OpenAI client to test that it works with this endpoint. First,
I ran `sg start minimal`. Then I wrote this script
```py
import os
from openai import OpenAI
from dotenv import load_dotenv
import httpx

load_dotenv()

openai = OpenAI(
    # base_url="https://api.openai.com/v1",
    # api_key=os.getenv("OPENAI_API_KEY"),
    base_url="https://sourcegraph.test:3443/api/v1",
    api_key=os.getenv("SRC_ACCESS_TOKEN"),
    http_client=httpx.Client(verify=False)
)

def main():
    response = openai.models.list()
    for model in response.data:
        print(model.id)
if __name__ == "__main__":
    main()

```
Finally, I ran 
```
❯ python3 models.py
anthropic::unknown::claude-3-haiku-20240307
anthropic::unknown::claude-3-sonnet-20240229
fireworks::unknown::starcoder
```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* New `GET /.api/llm/models` and `GET /.api/llm/models/{modelId}` REST
API endpoints to list available LLM models on the instance and to get
information about a given model. This endpoints is compatible with the
`/models` and `/models/{modelId}` endpoints from OpenAI.

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-14 10:47:00 +00:00
Julie Tibshirani
c222523fa5
Redis: remove some direct pool usages (#64447)
We want to discourage direct usage of the Redis pool in favor of routing
all calls through the main `KeyValue` interface. This PR removes several
usages of `KeyValue.Pool`. To do so, it adds "PING" and "MGET" to the
`KeyValue` interface.
2024-08-14 13:39:10 +03:00
Petri-Johan Last
d3a3d721d3
Add support for Bitbucket Server OAuth2 (#64179)
Docs here: https://github.com/sourcegraph/docs/pull/561

This PR adds support for using Bitbucket Server OAuth2 application links
for sign-in and permission syncing.

When used for permission syncing, the user's oauth token is used to
fetch user permissions (and now permissions are fetched via the server).

## Test plan

Tests added and updated.

## Changelog

- Sourcegraph now supports Bitbucket Server OAuth2 application links for
user sign-in and permission syncing.
2024-08-14 12:24:32 +02:00
Felix Kling
56e1f11f25
fix(svelte): Remove unnecessary console.log statement (#64463)
Did a ripgrep to see if there are any other `console.log` statements
that should be removed but this was the only one.

## Test plan

code inspection, trivial change
2024-08-14 10:22:14 +00:00
William Bezuidenhout
3b85035f56
chore: download - ensure dir exists when writing to dst (#64460)
Closes DINF-182

Before `sg start otel` would fail if `.bin` did not exist. We now create
the destination directory if it doesn't exist

## Test plan
1. `rm -rf .bin`
2. `sg start otel`

and unit tests + CI
## Changelog
* when downloading files, ensure the directory we download to exists
2024-08-14 09:14:40 +00:00
Craig Furman
bcb2e16d0b
feat(appliance): optionally load pinned releases file (#64441)
**chore(appliance): version list obtained from backend**

Instead of calling release registry directly from the frontend. This
commit is just preparation for a fallback mechanism for users that do
not want the external dependency on release registry.



**feat(appliance): optionally load pinned releases file**

Instead of calling release registry. This is a fallback mechanism for
airgap users.



**feat(appliance): respect pinned release versions during self-update**
2024-08-14 09:24:51 +01:00
Julie Tibshirani
ca6e72fe18
Redis: remove RedisKeyValue constructor (#64442)
This PR removes the `redispool.RedisKeyValue` constructor in favor of
the `New...KeyValue` methods, which do not take a pool directly. This
way callers won't create a `Pool` reference, allowing us to track all
direct pool usage through `KeyValue.Pool()`.

This also simplifies a few things:
* Tests now use `NewTestKeyValue` instead of dialing up localhost
directly
* We can remove duplicated Redis connection logic in Cody Gateway
2024-08-14 11:24:32 +03:00
Felix Kling
34ff925ed8
feat(svelte): Add cody chat page (#64448)
Closes #srch-906

This commit adds the cody chat page to svelte. This is simply reusing
the existing wrapper around the React component and renders it in a
standalone page.

When merged this will cause the cody chat page to be handled by new web
app on dotcom by default.

## Test plan

- Verified that chat loads and the tabs are clickable.
- Verified that the scroll behavior works as in the React app.
- Verified that the sidebar chat still works as expected (scroll
behavior, default context loading/switching)
2024-08-13 19:25:32 +00:00
Kalan
f9f3cd86ec
Add verbiage to direct Cody feedback to VSC/JB repos (#64454)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
N/A text only
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 19:18:46 +00:00
Robert Lin
043e780590
feat/enterpriseportal: add license creation webhook (#64422)
Closes https://linear.app/sourcegraph/issue/CORE-241
Originally added in
https://github.com/sourcegraph/sourcegraph/pull/59214

This seems unused, but might be good to have for completedness-sake

## Test plan

Unit tests
2024-08-13 12:11:03 -07:00
Robert Lin
2649987bac
fix/enterpriseportal: [MUST REVERT LATER] relax scopes for write operations (#64453)
Staging this PR in case we don't find a way to unblock
https://sourcegraph.slack.com/archives/C079SAU0E72/p1723573784387739?thread_ts=1723566345.486509&cid=C079SAU0E72.
If this passes CI first, I'll roll this out to Enterprise Portal to
unblock TS/CE

This is needed because we can't roll out
https://github.com/sourcegraph/sourcegraph/pull/64450 due to a stuck
migration

## Test plan

n/a
2024-08-13 11:58:49 -07:00
Camden Cheek
3522dcf4af
Svelte: fix file tree guide lines (#64425)
I think I broke this when doing some refactoring to make the file tree
usable in the ref panel. Currently, the guide lines only go one level of
depth.
2024-08-13 10:33:34 -06:00
Robert Lin
27d0615a3d
dotcom: request write scopes for EP prod proxy (#64450)
doh

## Test plan

n/a
2024-08-13 16:14:57 +00:00
Robert Lin
adce59be48
fix/enterpriseportal: adjust job check frequency, tweak messaging (#64418)
- The time.Second frequency is too frequent to be checking if the job
should be run, I think I set this in testing
- Adjust the Slack messaging to say `Active license`
- Adjust the Slack messaging to include the Salesforce subscription ID

## Test plan

Tests
2024-08-13 09:11:08 -07:00
Keegan Carruthers-Smith
f2fa76a8fd
migrations: remove support for NoTransaction (#64432)
This is a partial revert commit of
cbd12608b5.

We added support for NoTransaction but it isn't needed anymore. In fact
avoiding transactions leads to issues like poisoning connections.

Test Plan: CI
2024-08-13 16:08:36 +00:00
William Bezuidenhout
26f14c0888
ci: set go mod tidy step timeout (#64449)
Closes DINF-198

## Test plan
CI
```
{
      "label": ":bazel:🧹 Go mod tidy",
      "key": "bazel-go-mod",
      "command": [
        "./dev/ci/bazel-gomodtidy.sh"
      ],
      "timeout_in_minutes": "5",
      "retry": {
        "automatic": [
          {
            "limit": 1,
            "exit_status": "*"
          },
          {
            "limit": 1,
            "exit_status": -1
          }
        ]
      },
      "agents": {
        "queue": "aspect-small"
      }
    },
```

## Changelog
2024-08-13 17:45:30 +02:00
Keegan Carruthers-Smith
9d2220ea33
migration: specify column for soft delete triggers (#64446)
We believe the migration to add tenant_id is failing on dotcom is due to
this trigger which runs for any possible change to a row. Instead it
only needs to run if the deleted_at column changes. So this migration
just adjusts each trigger to only run if deleted_at is changed.

We don't need to change the trigger function, since the trigger
functions only read deleted at.

If this doesn't resolve our issue, we will need to look into a statement
level trigger for all our triggers.

Test Plan: CI and then will test safely on larger instances.
2024-08-13 15:03:49 +00:00
Shivasurya
3cb7ab8c6a
Support SAST Scanning with both GHAS and Custom post processing script (#64423)
This pull request supports buildkite semgrep sast scan to work on both
GHAS and with custom post processing script. This script checks if GHAS
is enabled or not and runs the semgrep scan and process the result. This
way we could support repositories without GHAS enabled.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

- CI 🟢 
- sast scans are reported without any issues

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- chore(security): Support SAST Scanning with both GHAS and Custom post
processing script
2024-08-13 09:43:09 -04:00
Felix Kling
9890086f94
fix(web): Show 'Find implementation' button for languages that support it (#64440)
Fixes srch-882

I noticed that the button wasn't shown anymore (neither in Svelte nor in
React). It seems that this broke when we switched from using the file
extension to getting the language(s) from the server.
The server sends back capitalized names which we compare against
lowercase IDs.

If there there is a new/modern way to find out whether a language
support 'find implementation' or not, please let me know. For the time
being this seems to be a simple fix to get it working again like it
before. Alternatively we can also compare the stylized name.

## Test plan

Hovering over a Go interface (e.g.
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/internal/conf/server.go?L12)
shows the 'find implementations' button in the hovercard again)
2024-08-13 15:40:03 +02:00
Felix Kling
3e734549c7
fix(svelte): Fix tooltip in hovercards (#64443)
Fixes srch-744

It seems that the code for testing whether the target element is part of
the layout didn't work in hovercards because it (possibly?) runs before
the hovercard is rendered.
Moving the logic to `onMount` + `await tick()` seem to work, although
that might still be a coincidence.

## Test plan

Hovering over the 'precise' badge shows the corresponding tooltip.
2024-08-13 15:39:35 +02:00
Felix Kling
df91f98feb
fix(svelte): Show tools section in top navigation sidebar mode (#64438)
Fixes srch-901

The CSS for sidebar mode wasn't updated after introducing the tools
menu.


## Test plan

Manual visual testing.
2024-08-13 13:24:36 +00:00
Felix Kling
9667975db6
fix(svelte): Show focus style when tabbing through search query examples (#64439)
## Test plan

Manual testing.
2024-08-13 12:11:28 +00:00
Keegan Carruthers-Smith
e93b69bef2
migrations: use COMMIT AND CHAIN for tenant_id (#64431)
We dived into our go postgres driver and when executing a migration it
is executed as a "simple query". Postgres in this case automatically
wraps the collection of statements in a transaction, unless it contains
transaction statements. So our last attempt at removing the transaction
failed.

In this attempt we use COMMIT AND CHAIN after each table alter. What
this does is commit the current transaction and then starts it up again.
From the perspective of the go driver, it is as if there was only one
transaction. We then switch the migration to using a transaction to
ensure the go drivers clean up the postgres connection in case of
failure.

IE if a query manually starts a transaction and does not clean up, the
connection will be marked as broken for the next person who gets the
connection from the pool. By wrapping in go's transaction code the
connection will be properly cleaned up.

Test Plan: All continuous environments have already succeeded or failed
on this migration number. So we will manually run this again against
them with the migrator code to ensure the same code paths. If they
succeed we will keep code as is, otherwise we will rollback.

Additionally we did lots of adhoc testing to understand the
characteristics of go and transaction handling.

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-08-13 11:59:59 +00:00
Ólafur Páll Geirsson
7b1bc10a30
chore/API: speed up edit/test feedback loop for llmapi module (#64437)
Previously, it took ~6 seconds for a single edit/test/debug feedback
loop in the `llmapi` module. After this change, it's now 1-2s.

The reason the feedback loop was slow was that we depended on the
`//cmd/frontend/internal/modelconfig` target, which transitively brings
in `graphqlbackend` and all the migration code, which adds huge overhead
to Go link times. It was relatively easy to untangle this dependency so
I went ahead and removed it to boost my local feedback loop.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
Green CI.

To measure the timing, I ran the tests, made a tiny change and ran the
tests against to measure the total time to build+test.

```
# Before
❯ time go test -timeout 30s github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi
ok  	github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi	2.394s
go test -timeout 30s   4.26s user 4.73s system 166% cpu 5.393 total

# After
❯ time go test -timeout 30s github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi
ok  	github.com/sourcegraph/sourcegraph/cmd/frontend/internal/llmapi	0.862s
go test -timeout 30s   1.20s user 1.21s system 135% cpu 1.774 total
```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 11:48:15 +00:00
Noah S-C
d4fa539b31
Revert "chore(ci): rework build-tracker to use redis instead of in-memory store of build results" (#64436)
Reverts sourcegraph/sourcegraph#64304

Number of redis related issues cropped up live

## Test plan

CI
2024-08-13 13:22:41 +02:00
Bolaji Olajide
4d57eb1188
fix(sg): make sg gen output more readable (#64406)
Closes DINF-78

The output of `sg gen` is a bit hard to read when there's an error, this
is because the new line character `\n` isn't rendered as a new line. It
turns out the `%q` formatting directive used to quote a string doesn't
render the `\n` character as a new line.

| Before |
|---|
| ![CleanShot 2024-08-12 at 11 17
57@2x](https://github.com/user-attachments/assets/e03ec503-e437-4b68-80b3-fe34ac8848fb)
|

| After  |
|---|
| ![CleanShot 2024-08-12 at 10 53
35@2x](https://github.com/user-attachments/assets/5b7aac63-27b6-4de0-9c56-3b739f0ee0f9)
|

I also added a func to extract error messages from a bazel command to
avoid long output message when a bazel command fails and give the user
relevant messages related to the error.

| Before  |
|---|


https://github.com/user-attachments/assets/2d029ec1-5804-41bf-a675-8642e169ea80


| After  |
|---|
| ![CleanShot 2024-08-12 at 14 45
59@2x](https://github.com/user-attachments/assets/7d567fd6-de37-48aa-b2b5-03dc591fc77a)
|

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

* Manual testing

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 06:22:21 -05:00
Noah S-C
67f30a9d7a
chore(ci): rework build-tracker to use redis instead of in-memory store of build results (#64304)
Currently, build-tracker keeps track of consecutive build failures
through an in-memory store of failed builds. As this gets deployed more
frequently on MSP, we lose state more frequently which would result in
incorrect results. Instead, we can use redis as our external store as
well as for locking using redsync

## Test plan

Unit tests have been updated, but proper testing will require live
traffic

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 10:32:09 +00:00
Ólafur Páll Geirsson
47b66397da
feat/API: move from /api/v1 to /.api/llm (#64435)
Fixes CODY-3269

Previously, the OpenAI-compatible API endpoints had paths like
`/api/v1/chat/completions`, which went against an existing convention of
keeping all APIs under the `/.api` prefix. We have a fair amount of
internal tooling centered around the assumption that APIs have the
`/.api` prefix so this PR corrects the mistake and moves the
`/api/v1/chat/completions` endpoint to `/.api/llm/chat/completions`.

I went with the prefix `/.api/llm` since these allow clients to interact
with LLM features like `/chat/completions` or listing model information.
These APIs happen to be compatible with OpenAI APIs but I think it will
be more confusing to add something like "openai" or "openaicomptable" in
the API endpoint. We can just document on our website that these
endpoints are compatible with OpenAI clients.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Green CI. I also manually confirmed that I was able to use an OpenAI
client to send requests to the new APIs.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* Moved `/api/v1/chat/completions` to `/.api/llm/chat/completions`. The
functionality is unchanged.

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 10:21:27 +00:00
Erik Seliger
6914068c8c
migrationtests: Actually run in a transaction when in test mode (#64434)
When we added a migration that actually relies on the promised property
of migrations always running inside a transaction, we noticed that the
memoryStore implementation we use in the dbtest package does not
actually start a transaction. This implements transactions for the
memorystore as well, to make it pass.

Test plan: Our migration now passes, and dbtest performance with and
without this change is the same.
2024-08-13 10:07:06 +00:00
Christoph Hegemann
a80ad938ce
fix: return all search-based results if no syntactic provenance is requested (#64330)
Closes
https://linear.app/sourcegraph/issue/GRAPH-797/return-all-search-based-results-if-syntactic-is-not-requested

Making sum-types like a caveman...

## Test plan

Manual testing via API. I can't make the web app do a search-based
usages request at the moment.
2024-08-13 10:52:56 +02:00
Ólafur Páll Geirsson
70aa6908ea
fix/API: make requests to /api/console work again (#64429)
Fixes CODY-3267

Previously, requests to `/api/` matched the new `publicrestapi` module,
which meant that requests to the GraphQL `/api/console` no longer
worked. This PR fixes the problem by narrowing the prefix-match to
`/api/v1` so that it no longer matches `/api/console`.

I kept the scope of this PR narrow and only fixed the /api/console bug.
I will share a separate RFC to seek input on the tradeoffs between
/api/v1 and /.api. I can make that change separately if there's wide
consensus in #wg-architecture that we want to keep all API endpoints
(public and internal-facing) under /.api.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Ran `sg start minimal` and confirmed that I'm able to visit the URL
https://sourcegraph.test:3443/api/console

On the main branch, the same URL leads to a 404 page.

I also confirmed that the `/api/v1/chat/completions` endpoint still
works as expected.

```hurl
POST https://sourcegraph.test:3443/api/v1/chat/completions
Content-Type: application/json
Authorization: Bearer {{token}}
{
  "model": "anthropic::unknown::claude-3-sonnet-20240229",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Respond with \"no\" and nothing else"
        }
      ]
    }
  ],
  "temperature": 1,
  "max_tokens": 256,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0
}
```
```sh
❯ hurl hurl-scratchpad/openai-sg.hurl
{"id":"chat-1727acdf-6850-4387-950b-2e89850071fa","choices":[{"finish_reason":"end_turn","index":0,"message":{"content":"no","role":"assistant"}}],"created":1723536215,"model":"anthropic::unknown::claude-3-sonnet-20240229","system_fingerprint":"","object":"chat.completion","usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
```

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-13 10:04:40 +02:00
Julie Tibshirani
2bbd84fac4
Redis: refactor key prefixing (#64411)
Our redis `KeyValue` interface has a built-in way to prefix all keys.
This is helpful for integration tests, to contain all keys within a test
namespace.

This PR solidifies the implementation by pushing down the prefixing as
much as possible. In doing so, it fixes a bug with the `Keys()` method
where we forgot to prefix the pattern. This makes it easier to add new
methods to the interface without forgetting to add the prefix.
2024-08-13 10:13:02 +03:00
Keegan Carruthers-Smith
cbd12608b5
database: run tenant_id migration outside of a transaction (#64410)
We hit a deadlock when deploying this migration to s2. This is because
within our transaction of the migration we likely didn't obtain table
locks in the same order as a transaction in our application code.

So this commit introduces a new migration metadata field
"noTransaction". The documentation for migrator says you should create a
migration per needed transactions. However, this would require us to
create 100s of migrations. We believe the better approach is introducing
this field and barely advertising it.

When reading the code which actually runs migrations, there is no extra
logic done outside of BEGIN; run_migration; COMMIT; so this change is
safe.

We update the migrations to avoid duplicating the function name we
introduce in case something goes wrong (now that the transaction could
leak out the function name).

Test Plan: The actual migrations are tested by go test. I added a test
assertion that we don't call Transact, but to be honest that is super
sketchy. However, we couldn't actually find any test fixtures which
actually run against the DB. So that would require a much deeper
investment for how simple the code change is.

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-08-13 07:08:19 +02:00
Michael Lin
20f22d29f0
sg/cloud: fix eph cmd typo (#64427)
fixed typo. these commands are under `sg cloud eph`

## Test plan

CI
2024-08-13 06:53:07 +02:00
Jacob Pleiness
b5d7a4f598
fix(release): add minor step to internal release create command (#64377)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

This PR adds the ability to use `--type minor` when running `sg release
create` during the release process.

For the time being this step is the _same_ as `--type patch` which is
the default, however this allows us to differentiate the two types now
and prepares for when/if the two types diverge. This also clears up the
some confusion as the `sg release` command _can_ accept `--type minor`
already and one would expect that to be the choice when you are in fact
cutting a minor type.

Closes:
https://linear.app/sourcegraph/issue/REL-351/sourcegraphsourcegraph64377-fixrelease-add-minor-step-to-internal

## Test plan

Tested locally with `--type minor` tag.

```shell
➜  sourcegraph git:(08-08-jdp_release_minor-flag-addition) sg release create --version 5.6.877 --type minor
👉 [     setup] Finding release manifest in "."
   [     setup] No explicit branch name was provided, assuming current branch is the target: 08-08-jdp_release_minor-flag-addition
   [     setup] Found manifest for "sourcegraph" (github.com/sourcegraph/sourcegraph)
   [      meta] Owners: @sourcegraph/release
   [      meta] Repository: github.com/sourcegraph/sourcegraph
👉 [      vars] Variables
   [      vars] version="v5.6.877"
   [      vars] tag="5.6.877"
   [      vars] config="{\"version\":\"v5.6.877\",\"inputs\":\"\",\"type\":\"minor\"}"
   [      vars] git.branch="08-08-jdp_release_minor-flag-addition"
   [      vars] is_development="false"
.... Stuff here
   [ buildkite] Build created, see:
   [ buildkite] "https://buildkite.com/sourcegraph/sourcegraph/builds/287192"
   [      step] Step "buildkite" succeeded
```

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

Internal change, N/A

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-12 19:48:18 -04:00
Camden Cheek
a9b536cbcd
Chore: fix default value for clientSearchResultRanking (#64420)
The search clients [default to using Zoekt's
ranking](https://sourcegraph.com/github.com/sourcegraph/sourcegraph@f010787579fc0b88ef945a6cfd0091c58eefceeb/-/blob/client/web-sveltekit/src/routes/search/FileContentSearchResult.svelte?L29-29)
if this setting is unset, but it's documented as defaulting to ordering
by line number. Just fixes the default in the schema, which is only used
for documentation.
2024-08-12 22:47:08 +00:00
Varun Gandhi
74f4831aa3
chore: Replace gitserver.Client -> minimalGitserver in codenav (#64416)
In codenav, we use very few APIs from gitserver, so let's use a more
narrow interface (which we can potentially fake in the future) instead
of depending on gitserver.Client directly.
2024-08-12 16:40:36 -04:00
Keegan Carruthers-Smith
6a28eb85bb
tenant: set pprof label for tenant (#64338)
In the future this will allow us to attribute stack traces collected by
pprof to a tenant. This only sets it for the http middleware. I am
unsure how to achieve the same thing for grpc, since that uses
propogators.

Test Plan: captured a goroutine profile and saw some goroutines with a
tenant label

---------

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-08-12 19:40:26 +00:00
Keegan Carruthers-Smith
520444ef61
linters: update go-critic to latest (#64419)
I was tired of seeing this warning when running gazelle:

  gazelle: finding module path for import github.com/go-critic/go-critic/framework/linter: go: downloading github.com/go-critic/go-critic v0.11.4
  go: module github.com/go-critic/go-critic@upgrade found (v0.11.4), but does not contain package github.com/go-critic/go-critic/framework/linter

This updated go-critic to the latest version which makes the warning go
away since it now uses the new package path.

Test Plan: gazelle is happy and CI is happy
2024-08-12 21:30:49 +02:00
Robert Lin
cec288dc89
fix/enterpriseportal, fix/codygateway: zero-value durations and missing active licenses (#64378)
This change ensure we correctly handle:

1. In Enterprise Portal, where no active license is available, we return
ratelimit=0 intervalduration=0, from the source `PLAN` (as this is
determined by the lack of a plan)
2. In Cody Gateway, where intervalduration=0, we do not grant access to
that feature

## Test plan

Unit tests
2024-08-12 11:49:54 -07:00
Keegan Carruthers-Smith
3edfaa8db6
migration: make stitch tests run in 7s (#64417)
This change caches what we download from google storage.

Before this change on my desktop computer this test would timeout after
10 minutes. It now takes 4s.

Test Plan: go test ./internal/database/migration/stitch
2024-08-12 18:38:08 +00:00
Keegan Carruthers-Smith
5bc97d9f03
migration: fix stitch test cases (#64409)
These all fail and are only run outside of bazel (which is why we didn't
notice it). I believe the root cause is google getting more strict with
the URLs you pass it.

Should we consider removing these tests given no one has reported it not
working? Or should we get it working in Bazel?

Test Plan go test ./internal/database/migration/stitch/
2024-08-12 20:27:10 +02:00
Camden Cheek
1e3b643e94
Search blitz: updates for 3rd-party users (#64375)
The goal of this PR is to make search blitz usable for customers who
want to run it against their instance for continuous performance
analysis.

Specifically, this does two things:
1) Enables configuring the set of queries to run with the
`SEARCH_BLITZ_QUERY_FILE` env var
2) Packages the image in our standard format so we can publish it
2024-08-12 16:13:06 +00:00
Jacob Pleiness
59ad280fe1
feat(appliance): nodeexporter service definition (#64399)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

Relates to
https://linear.app/sourcegraph/issue/REL-80/service-definition-node-exporter

## Test plan

Golden tests included.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-12 11:36:41 -04:00
Jacob Pleiness
72e1838b4c
fix(appliance): bypass setupenv-test for local testing if not installed (#64305)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

Bypass the requirement for
`sigs.k8s.io/controller-runtime/tools/setup-envtest` when running `go
test` in the `internal/appliance` package.

Previously running `go test` without
`sigs.k8s.io/controller-runtime/tools/setup-envtest` installed would
fail the tests that required it. This changes this behavior to instead
skip the tests requiring `setup-envtest` if the user doesn't have it
installed locally.

## Test plan

Tested locally without `setup-envtest` installed:
```shell
go test ./internal/appliance/reconciler... -v
=== RUN   TestApplianceTestSuite
    helpers_test.go:37: setup-envtest is not installed, skipping ApplianceTestSuite
--- SKIP: TestApplianceTestSuite (0.00s)
PASS
ok  	github.com/sourcegraph/sourcegraph/internal/appliance/reconciler	0.907s
```

Tested locally with `setup-envtest` installed:
```shell
go test ./internal/appliance/reconciler... -v
...
        --- PASS: TestApplianceTestSuite/TestDeployWorker/worker/with-blobstore (0.25s)
        --- PASS: TestApplianceTestSuite/TestDeployWorker/worker/with-replicas (0.24s)
    --- PASS: TestApplianceTestSuite/TestDoesNotDeleteUnownedResources (0.22s)
    --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenPGSecretsChange (1.36s)
        --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenPGSecretsChange/pgsql-auth (0.47s)
        --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenPGSecretsChange/codeinsights-db-auth (0.44s)
        --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenPGSecretsChange/codeintel-db-auth (0.45s)
    --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenRedisSecretsChange (0.93s)
        --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenRedisSecretsChange/redis-cache (0.45s)
        --- PASS: TestApplianceTestSuite/TestFrontendDeploymentRollsWhenRedisSecretsChange/redis-store (0.48s)
    --- PASS: TestApplianceTestSuite/TestMergeK8sObjects (0.00s)
        --- PASS: TestApplianceTestSuite/TestMergeK8sObjects/Successful_merge (0.00s)
        --- PASS: TestApplianceTestSuite/TestMergeK8sObjects/Merge_with_overlapping_keys (0.00s)
        --- PASS: TestApplianceTestSuite/TestMergeK8sObjects/Merge_with_empty_new_object (0.00s)
        --- PASS: TestApplianceTestSuite/TestMergeK8sObjects/merges_annotations (0.00s)
    --- PASS: TestApplianceTestSuite/TestNonNamespacedResourcesRemainWhenDisabled (0.45s)
    --- PASS: TestApplianceTestSuite/TestResourcesDeletedWhenDisabled (0.45s)
    --- PASS: TestApplianceTestSuite/TestStandardFeatures (2.43s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/blobstore-with-named-storage-class (0.24s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/frontend-with-no-cpu-memory-resources (0.25s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/precise-code-intel-with-env-vars (0.24s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/redis-with-multiple-custom-images (0.25s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/redis-with-storage (0.25s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/repo-updater-with-no-resources (0.26s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/repo-updater-with-pod-template-config (0.23s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/repo-updater-with-resources (0.25s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/repo-updater-with-sa-annotations (0.24s)
        --- PASS: TestApplianceTestSuite/TestStandardFeatures/standard/symbols-with-custom-image (0.23s)
PASS
ok  	github.com/sourcegraph/sourcegraph/internal/appliance/reconciler	20.576s
```

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog
N/A as this is not a user facing change.
<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-12 11:27:36 -04:00
Jean-Hadrien Chabran
991355ba02
chore(ci): shard authz test (#64413)
Similar to https://github.com/sourcegraph/sourcegraph/pull/64412 

## Test plan

CI
2024-08-12 14:50:01 +00:00
Jean-Hadrien Chabran
4d21a3e68f
chore(ci): shard //internal/repos:repos_test (#64412)
See
https://buildkite.com/organizations/sourcegraph/analytics/suites/sourcegraph-bazel/tests/d047e8dd-c849-8a8b-8925-41c2b8e58ec9?branch=main,
this particular test target tends to timeout on occasions, because it
goes over the `short` timeout.

By sharding it, we could hope it would be more stable. So, time will
tell if that was worth it. Right now, analytics shows that it goes down
to 10s with four shards, which is faster that most runs.

## Test plan

CI
2024-08-12 14:39:29 +00:00
Keegan Carruthers-Smith
f517373f22
tenant: pprof for missing tenant in FromContext (#64405)
Instead of adding instrumentation for each place we expect a tenant, we
instead assume that we always expect a tenant if FromContext is called.
This should allow us to not miss any places.

Note: this does remove the logging we had in diskcache, but it seems
more reasonable to just use pprof for something that can be noisy?

Test Plan: just gonna rely on CI since this defaults to off.
2024-08-12 13:00:03 +00:00
Julie Tibshirani
e65e736cb1
Redis: simplify DeleteAllKeysWithPrefix (#64407)
The `DeleteAllKeysWithPrefix` method is now only used in tests to ensure
the test keyspace is clear. This PR makes it clear this method is only
used in tests, and simplifies the implementation so it no longer needs a
script + direct Redis connection.

Another tiny Redis refactor to prepare for multi-tenancy work.
2024-08-12 15:25:33 +03:00
Julie Tibshirani
fae95fdf13
Search: boost phrases in hybrid search (#64367)
This PR passes the 'boost' annotation down to searcher, so that it can
apply phrase boosting. For now, we just pass the boost to the Zoekt
query in hybrid search, which already gives a nice benefit since the
Zoekt results are streamed back first.

Note: this doesn't completely implement boosting in searcher, but it was
really simple and seemed worth it. We're purposefully not investing in
big searcher ranking improvements, since we think a better investment is
to unify logic across Zoekt + searcher.
2024-08-12 11:24:51 +03:00
Robert Lin
02ac0214ee
chore/enterpriseportal: manual E2E test suite (#64057)
Adds a super simple E2E test suite that must be run with `sg test
enterprise-portal-e2e` against a locally running Enterprise Portal
instance. This is not intended to be filled with super granular
assertions - it simply tests that everything is wired up correctly and
runs end-to-end.

Caught at ~3 issues with this already, amended various downstack PRs
with the fix 😆

Closes
https://linear.app/sourcegraph/issue/CORE-229/enterprise-portal-basic-manual-e2e-testing-setup

## Test plan

```
sg start dotcom
sg test enterprise-portal-e2e
```

No additional configuration required, the defaults work as-is
2024-08-09 19:37:52 -07:00
Robert Lin
082535836a
feat/enterpriseportal: add instance category (#64253)
Per some feedback around
https://docs.google.com/document/d/1NyBIQvZ-ziNhiz7Yuzbp4f72Gp6EUrVUoBYnnnviXi8/edit,
this adds a "instance type" enumeration for each subscription:

1. PRIMARY: production
2. SECONDARY: dev/testing/staging/whatever
3. INTERNAL: for us

## Test plan

Updated tests
2024-08-09 18:19:51 -07:00
Robert Lin
e2c646ad92
feat/enterpriseportal: all subscriptions APIs use enterprise portal DB (#63959)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the
_all_ subscriptions APIs read and write to the Enterprise Portal
database, instead of dotcomdb, using the data that we sync from dotcomdb
into Enterprise Portal.

With this PR, all initially proposed subscriptions APIs are at least
partially implemented.

Uses https://github.com/hexops/valast/pull/27 for custom `autogold`
rendering of `utctime.Time`

Closes https://linear.app/sourcegraph/issue/CORE-156
Part of https://linear.app/sourcegraph/issue/CORE-158

## Test plan

- [x] Unit tests on API level
- [x] Adapters unit testing
- [x] Simple E2E test:
https://github.com/sourcegraph/sourcegraph/pull/64057
2024-08-09 17:26:18 -07:00
Felix Kling
8296e9804f
feat(svelte): Migrate dotcom community search pages to Svelte (#64388)
What: This PR does the bare minimum to migrate the current community
search pages to Svelte. A better strategy for managing them is needed in
the medium/long term.

How: The community pages live at the root (e.g. `/kubernetes`) which
complicates things, but I'll get to that later. The page is implemented
as a single parameterized route. A parameter matcher is used to validate
the community name. Because these pages should only be accessible on
dotcom the matcher also validates whether or not we are on dotcom (if
not, the path will be matched against a different route).

The page config is stored in a separate module so that it's no included
in every page and so that it can be used in the integration test.

The loader and page implementation themselves are straightforward. I
made a couple of changes in other modules to make implementation easier:

- Extracted the parameter type of the `marked` function so that it can
be used as prop type.
- Added an `inline` option to `marked` that allows formatting markdown
as 'inline', i.e. without `p` wrapper.
- Added a `wrap` prop to `SyntaxHighlightedQuery.svelte` to configure
line wrapping of syntax highlighted search queries (instead of having to
overwrite styles with `:global`).
- Extended the route code generator to be able to handle single
parameter segments and the `communitySearchContext` matcher.

Because the community routes should only be available on dotcom I added
a new tag to the code generator that allows it include routes only for
dotcom.
Once we change how all this works and have community search pages live
under a different path we can simplify this again.

Result:

| React | Svelte |
|--------|--------|
|
![2024-08-09_16-05](https://github.com/user-attachments/assets/a64c4e0c-a9dd-4248-9466-05b348559408)
|
![2024-08-09_16-04](https://github.com/user-attachments/assets/d8ad424b-d04a-4590-b198-a6b2f4a76816)
|


## Test plan

- New integration tests.
- Verified that `/kubernetes` shows a 'repo not found error' when
running against S2.
- Verified that `/kubernetes` shows the community page when running
against dotcom.
- Verified that `window.context.svelteKit.enabledRoutes` contains the
community page route in enterprise mode but not in dotcom mode.
2024-08-09 22:52:47 +02:00
Camden Cheek
f1060eccac
Svelte: add support for navigating search results with the keyboard (#64257)
This adds support for navigating between search results with keyboard
shortcuts. Similar to the React app, `j` or `down` means "next result",
and `k` or `up` means previous results. To accompany this change, when a
search is submitted, the first result is focused by default to
facilitate iterating over results with the keyboard.
2024-08-09 14:24:05 -06:00
Camden Cheek
3df76cb173
Explore panel: more granular file tree (#64372)
The first version of the file tree for the revision panel had flat file
names. This meant that files were not organized, they were very
horizontal-space-sensitive, and you could not filter to a directory
(only repo and file name).

This updates the file filter to be a full tree, which I find much easier
to use.
2024-08-09 17:14:09 +00:00
Robert Lin
0de249daf9
feat/enterpriseportal: more list options for subscriptions and licenses (#64114)
Required to build an updated subscriptions management UI.

Most of the diff is generated proto for some reason

Closes https://linear.app/sourcegraph/issue/CORE-226

## Test plan

Integration tests
2024-08-09 16:43:39 +00:00
Taras Yemets
14a4d7ce31
fix(cody): filter out deprecated models (#64381) 2024-08-09 16:37:42 +00:00
Robert Lin
8537000f9d
feat/enterpriseportal: existing subscriptions read APIs use enterprise portal DB (#63927)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the
existing subscriptions APIs _read_ from the Enterprise Portal database,
instead of dotcomdb, using the data that we sync from dotcomdb into
Enterprise Portal.

Part of https://linear.app/sourcegraph/issue/CORE-156
Part of https://linear.app/sourcegraph/issue/CORE-158

## Test plan

Updated unit and integration tests
2024-08-09 09:36:40 -07:00
Robert Lin
3e9fe3a0b9
chore/enterpriseportal: make sf_opp_id license-level (#64087)
Per feedback on
https://docs.google.com/document/d/1NyBIQvZ-ziNhiz7Yuzbp4f72Gp6EUrVUoBYnnnviXi8/edit#heading=h.3lhmwnxotdew
and further research, the salesforce opportunity ID must be
license-level. Right now we keep this specific to the "license key"
license type.

## Test plan

CI
2024-08-09 16:16:37 +00:00
Robert Lin
43184a3dfe
feat/enterpriseportal: license expiry checker (#64317)
Port of the existing background job:
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/cmd/frontend/internal/dotcom/productsubscription/license_expiration.go?L25:6-25:45,
originally added in
https://github.com/sourcegraph/sourcegraph/pull/10362

Most of the diff is generated mocks :)

Closes https://linear.app/sourcegraph/issue/CORE-183

## Test plan

- [x] Unit tests
- [x] Manual test:
```
[enterprise-...l] INFO service.licenseexpiration.store licenseexpiration/store.go:96 PostToSlack {"text": "The license for subscription `coreservices - Robert Lin - 2024-07-16 23:16:13` <https://sourcegraph.com/site-admin/dotcom/product/subscriptions/bee0a0d9-6c17-4acf-81a4-fd6e777ed6a4|will expire *in the next 24 hours*> 🚨"}
```
2024-08-09 09:08:59 -07:00
Jean-Hadrien Chabran
2df3a40744
chore(ci): bump the tag on which backcompat operates (#64387)
Backcompat test suite works by checking out the code at the previous
minor release, injects the database schema from `HEAD` and run all Go
tests. This ensures that the old code can run against the new schema,
thus being backward compatible.

We forgot to update this the last time, that's why I'm bumping by two
tags here.

## Test plan

CI
2024-08-09 13:17:08 +00:00
Erik Seliger
ba9fe24e0f
Revert "tenant: Introduce tenant_id to every table (#64323)" (#64386)
This reverts commit 43e06cef0c.

This migration deadlocked on S2, we didn't expect that we have processes
taking table locks but apparently so.. Reverting for now and will
manually fix up S2 once the build went through. We probably need to make
this one migration per table :rip:

## Test plan

Revert.
2024-08-09 15:02:12 +02:00
Felix Kling
c4ea4b64d0
chore(web): Upgrade playwright (#64384)
The new version seems to be able to handle TypeScript aliases, using
`$lib` or `$testing` in playwright tests should now work.

## Test plan

CI
2024-08-09 13:01:46 +00:00
Noah S-C
c4fefc1fe6
chore(local): dont buffer sg updatecheck commencement notice (#64329)
Previously, `sg` would give no notice that an auto-update of itself was
happening in the background, due to background output being buffered.
This would be confusing when an invocation hangs/doesnt terminate as
quickly as expected due to the update process still being in progress.
Instead, we should print at least certain output from the process
immediately

## Test plan

`go run ./dev/sg -- <some command>` with a time.Sleep

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-09 14:33:40 +02:00
Greg Magolan
c60ae9cd67
build(bazel): upgrade to rules_oci 2.0.0-beta2 (#64364)
beta2 release came out yesterday. A few minor fixes on top of beta1.

https://github.com/bazel-contrib/rules_oci/releases/tag/v2.0.0-beta2

## Test plan

CI

## Changelog
2024-08-09 13:32:12 +01:00
Julie Tibshirani
0960775782
Redis: always use pointer receiver in keyvalue (#64385)
All other methods take a pointer receiver, so we should be consistent
and avoid unnecessary copying.
2024-08-09 14:21:04 +03:00
Anton Sviridov
db87eb601b
Use correct DSN for schema validation in syntactic worker (#64383)
Connecting to the wrong DSN leads to a cryptic error:

```
      Message:     {"SeverityText":"FATAL","Timestamp":1723196934012096886,"InstrumentationScope":"init db (syntactic-codeintel-worker)","Caller":"shared/shared.go:87","Function":"github.com/sourcegraph/sourcegraph/cmd/syntactic-code-intel-worker/shared.initCodeintelDB","Body":"Failed to connect to codeintel database","Resource":{"service.name":"syntactic-code-intel-worker","service.version":"286647_2024-08-08_5.6-34a7914fb884","service.instance.id":"syntactic-code-intel-worker-7bb9ccc75c-mkzpk"},"Attributes":{"error":"database schema out of date"}}
```

## Test plan
- existing tests should continue to pass


<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-09 11:21:33 +01:00
Jean-Hadrien Chabran
883604b925
chore(local): fix outdated frontend target being used (#64382)
In https://github.com/sourcegraph/sourcegraph/pull/63946 we reworked how
we handle assets, but we overlooked updating the target in
`sg.config.yaml`.

## Test plan

CI + locally tested (made some changes on the home page, got reloaded as
expected)
2024-08-09 09:41:52 +00:00
Ólafur Páll Geirsson
ba85ea6f32
feat/API: add publicly available /api/v1/chat/completions REST endpoint (#64239)
Fixes CODY-3081

This is the first PR for the project [⏭️ Launch Cody API
Experimental](https://linear.app/sourcegraph/project/launch-cody-api-experimental-8fd5ec338bf4),
which falls under the umbrella of moving Cody's brains to the cloud.

Previously, there was no publicly available REST API for our customers
to interact with Cody. This is a frequently requested feature from
customers and prospects.

This PR adds a new `POST /api/v1/chat/completions` endpoint, which
should be compatible with existing OpenAI clients. The OpenAI API format
is increasingly becoming an industry standard so this seems like a good
first step towards exposing a stable publicly facing API for our
customers.

The goal is to add more Cody-specific APIs in the coming weeks to send
chat messages and reference context.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

See added test cases.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

* API: new publicly available `/api/v1/chat/completions` REST endpoint
that is compatible with OpenAI clients with some restrictions. The detailed list of restrictions will eventually be documented on sourcegraph.com/docs

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-09 09:36:27 +00:00
Erik Seliger
43e06cef0c
tenant: Introduce tenant_id to every table (#64323)
We introduce the tenant_id column to every table without any magic
enforcement or magic default value. Instead we default to NULL and plan
to have an out of band migration. From out testing this change is
instant since it is only a table metadata change. According to the
documentation this sort of ALTER TABLE is instant since Postgres 11.

Test Plan: ran this migration against a clone of the s2 database.

---------

Co-authored-by: Keegan Carruthers-Smith <keegan.csmith@gmail.com>
2024-08-09 10:17:21 +02:00
Erik Seliger
7ad393bb35
db: Don't lose context when marking savepoints as done (#64361)
Currently, this uses context.Background, because the initial context
might've been canceled.
However, that causes us to lose any context involved here, so traces
won't include this query and tenant information would be lost.

This uses the new-ish context.WithoutCancel to avoid this issue and
stores the context used to create the transaction to close it later.

Test plan: Ran a local instance and didn't see errors, also integration
and E2E tests pass.
2024-08-09 10:16:06 +02:00
Stefan Hengl
f175436a73
tenant: update test to enforce tenant (#64379)
I forgot this when I added the test, so we were basically testing the
same thing twice.

## Test plan:
updated unit test
2024-08-09 10:03:41 +02:00
Julie Tibshirani
7402cd7769
Search: update Zoekt for telemetry improvement (#64380)
acacc5eda1...20c496e368

- https://github.com/sourcegraph/zoekt/commit/b4193c29e7 Remove
redundant phrase boost logic
- https://github.com/sourcegraph/zoekt/commit/801a704725 inline ctags
alpine script
- https://github.com/sourcegraph/zoekt/commit/e77b32d6f1 docker: remove
scip-ctags from Dockerfile
- https://github.com/sourcegraph/zoekt/commit/e372e97c88 Fix rare
failures in ngram selection tests
- https://github.com/sourcegraph/zoekt/commit/20c496e368 Add metric for
indexing delay
2024-08-09 11:03:13 +03:00
Julie Tibshirani
786a4753c0
Search: avoid phrase boost for non-text searches (#64369)
To ease the transition from older search semantics to keyword search, we
[boost matches on
phrases](https://github.com/sourcegraph/sourcegraph/pull/59940). This
phrase boosting applied to all search types, including repo, and symbol
searches. However, these search backends don't effectively handle the
extra boosted OR clause, so it can hurt performance and ranking.

This PR limits the phrase boosting to text searches (`type:file` and
`type:path`), as they benefit most from the boosting and can handle it
efficiently.
2024-08-09 10:09:03 +03:00
Naman Kumar
d0b88533b4
Remove old Cody Web completely (#64345)
closes:
https://linear.app/sourcegraph/issue/SRCH-622/remove-old-cody-web-entirely

Removes the old Cody Web completely.

## Test plan

- sg start
- visit /cody/chat and you should see the new unified panel Cody Web
without having to turn on any feature flags.
- check the blob view sidebar for the same.
## Changelog

- The new Cody Web is enabled by default and the older version of Cody
Web is completely removed from both standalone chat and sidebar.
2024-08-09 10:25:59 +05:30
Greg Magolan
119f17578c
build(bazel): upgrade to latest aspect bazel-lib and rules_js rules (#64365)
Some analysis phase performance improvements in rules_js 2.0.0-rc9 that
are worth picking up. rules_js is very close to 2.0.0 final now. Waiting
on one last improvement requiring and API change for bzlmod.

## Test plan

CI

## Changelog
2024-08-08 16:57:54 -07:00
Robert Lin
7c2d97858a
feat/dotcom: UI tracks Cody Gateway access directly in Enterprise Portal (#64090)
Upgrades the self-contained Cody Gateway modal to only depend on
Enterprise Portal to read/write Cody Gateway access.

I also made some minor tweaks to parsing empty form inputs, and also
made the "Cody Gateway access token" collapsed by default, with warnings
to discourage its use (opted not to remove entirely since it may be
useful for dev/debugging)

Depends on:

- https://github.com/sourcegraph/sourcegraph/pull/63926 
- https://github.com/sourcegraph/sourcegraph/pull/63925 
- https://github.com/sourcegraph/sourcegraph/pull/63858 

Closes https://linear.app/sourcegraph/issue/CORE-218

## Test plan

```
sg start dotcom
```

Edit the Cody Gateway access stuff, toggling it up and down.
Cross-reference with the `enterprise_portal_cody_gateway_access` table.
2024-08-08 16:37:16 -07:00
Robert Lin
447570628b
fix/enterpriseportal/codyaccess: allow removing rate limit overrides (#64376)
On double-checking the various Cody Gateway access management CRUD I
noticed that I did not implement the ability to remove the override
entirely properly - right now, removing a rate limit with `field_mask`
and no values results in a zero-value rate limit rather than a null one
as desired.

This change makes it so that if you provider a nil `*_rate_limit`
object, all field paths for that object is also set to nil, removing the
override and allowing the default active-license-plan-based rate limits
to apply.

This also adds a minor adjustment to Cody Gateway to correctly handle
zero durations for rate limit intervals, which should be treated as "no
access".

## Test plan

Unit/integration tests, and a manual test:

- Check out https://github.com/sourcegraph/sourcegraph/pull/64090 and
run `sg start dotcom`
- Go to a subscription, add a rate limit override 

![image](https://github.com/user-attachments/assets/9f417a60-5096-4f6e-8eea-1f0720cb4ada)
- Click the 🗑️ button to remove the rate limit override 

![image](https://github.com/user-attachments/assets/d53f4ae9-43d9-4bb2-a33b-7632f74ea2c8)
- Repeat above on each property
2024-08-08 15:19:58 -07:00
Robert Lin
076498f2dc
feat/enterpriseportal: implement UpdateCodyGatewayAccess (#63926)
Implements the only Cody Access write API we have right now, the ability
to apply overrides to Cody Gateway rate limits, which we'll have in
Enterprise Portal with
https://github.com/sourcegraph/sourcegraph/pull/63858

A lot of the diff is a new generated mock for the Cody Access store so
that we can write some simple unit tests.

With this addition, all initially proposed Cody Gateway access APIs are
implemented.

Part of https://linear.app/sourcegraph/issue/CORE-218
Closes https://linear.app/sourcegraph/issue/CORE-160

## Test plan

Unit and existing integration tests
2024-08-08 13:21:18 -07:00
Peter Guy
b625bea201
Doc and README update: Replace all usages of GH discussions with the SG community link. (#64374)
Sourcegraph's GitHub discussions have been defunct for awhile, but links
to them persisted in READMEs and documentation.

## Test plan

Documentation update only.
2024-08-08 13:04:13 -07:00
Naman Kumar
2dd38b3ffd
Fix Cody Web CSS (#64370)
closes:
https://linear.app/sourcegraph/issue/SRCH-866/improve-cody-web-theming-for-consistency-with-rest-of-product

This PR updates the Cody Web CSS based on the changes requested by
@rrhyne.

Few buttons implemented in Cody doesn't satisfy the design requirements
and do not use the css variable so we couldn't update them easily but
rather had to override the styles.

## Test plan

Before: 
![CleanShot 2024-08-08 at 22 53
48@2x](https://github.com/user-attachments/assets/95e10b42-b740-4663-a761-69449ec62296)

After:
![CleanShot 2024-08-08 at 22 54
12@2x](https://github.com/user-attachments/assets/bffbd10a-c87b-4eca-9582-b23eebccb60e)


## Changelog

- Make Cody Web styles more accessible.
2024-08-09 01:21:09 +05:30
Robert Lin
05ca108105
feat/enterpriseportal: use database for reading Cody Gateway access (#63925)
This change follows
https://github.com/sourcegraph/sourcegraph/pull/63858 by making the Cody
Access APIs _read_ from the Enterprise Portal database, instead of
dotcomdb, using the data that we sync from dotcomdb into Enterprise
Portal.

As part of this, I also expanded the existing "compatibility" test suite
that compares the result of our dotcomdb queries against the existing
GraphQL resolvers in dotcom to also compare the results of our new Cody
Access APIs, to validate that they return the same access.

> [!WARNING]
> There is one behavioural change, which is that hashes of _expired
licenses_ will no longer be valid as access tokens. This shouldn't be an
issue if customers use zero-config (implied access token from their
license key) - I will do some outreach before rolling this out.

Subsequent PRs will implement write APIs.


Part of https://linear.app/sourcegraph/issue/CORE-218
Part of https://linear.app/sourcegraph/issue/CORE-160

## Test plan

Integration and unit tests at various layers
2024-08-08 10:39:14 -07:00
Stefan Hengl
34a7914fb8
tenant: update FromContext to return error (#64363)
This updates `FromContext` to return an error instead of bool.

Follow-up from comment in
[#64335](https://github.com/sourcegraph/sourcegraph/pull/64335#discussion_r1708886602)

Test plan:
CI
2024-08-08 16:59:53 +02:00
Keegan Carruthers-Smith
ea55d761ba
database: optional pprof for tenantless_queries (#64337)
This adds a new profile output for when a sql query does not have a
tenant set. This can be downloaded like other pprof profiles and
inspected by "go tool pprof". This allows us to easily see the most
common stack traces and sources of missing context.

Test Plan: downloaded from the debugserver the new profile type and
inspected with "go tool pprof"

---------

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-08-08 14:18:59 +00:00
Felix Kling
e0702bea7d
build(svelte): Build Svelte app with enterprise runset (#64355)
Fixes srch-867

This commit adds a new command, `web-sveltekit-prod`, which simplies
builds the SvelteKit app and exits.
This command is now run by default when using `sg start`, so the assets
will be available locally.

Note however that the build process is quite slow, which is why I didn't
make it rebuild on file changes. Using the vite dev server, e.g. via `sg
start enterprise-sveltekit`, delivers a much better experience.

To make the integration a bit more ergonomic, I made additional changes:

- When run via `sg` (determined by checking `DEPLOY_TYPE`) compiler
warnings are not printed. That reduces noise in the `sg` output.
- I made similar changes to the svelte check bazel target to make it
easier to spot actuall errors (warnings are still important to fix but
since they don't cause the target to fail they just make it difficult to
spot the actual error).
- Since I finally found out about the `onwarn` handler, I made it so
that warnings about missing declarations are ignored. These warnings
occur for every icon because the Svelte compiler doesn't respect ambient
d.ts files.
- And since I made icon warning related changes I also documented a bit
how icons work in the app.

## Test plan

- `sg start` runs the `web-sveltekit-prod` command and the Svelte app is
served when going to `https://sourcegraph.test:3443/search`.
- The output of `bazel test //client/web-sveltekit:svelte-check` now
only contains errors.
- The output of `pnpm dev` (vite devserver) shows warnings that are not
related to icons.
2024-08-08 16:18:29 +02:00
Felix Kling
97ef93ddac
fix(svelte): Always close navigation sidebar when navigating to a different page (#64357)
Fixes srch-859

Problem: Currently the sidebar can reopen in the following scenario:
- Go to search home and submit a search
- On the search results page click the menu icon to open the sidebar and
click 'Code Search' to go back to search home.
- Execute a different query
- -> this brings you back to search results but with the menu sidebar
open

Looking at the code it's understandable that this happens: We never
close the sidebar. But this problem wasn't very visible because every
entry in the nav sidebar either brings you to the React app or to a page
with inline nav menu.

So this commit fixes the issue by closing the sidebar whenever we
navigate to a different page.

## Test plan

Manual testing. I added a temporary nav entry that would bring me to the
sourcegraph repo page. Clicking on it from the search results page
caused the sidebar to close.
2024-08-08 16:18:07 +02:00
William Bezuidenhout
cacc01be6f
ci: provide a more descriptive error when pipegen fails (#64362)
Give a more descriptive error when we are unable to find a merge base
and can't find the files that have changed.

Closes DINF-162
## Test plan
1. `git fetch -v --prune --depth=100 -- origin
ccbaba24b72f3c6f4524b3f560ca839143ea463b`
2. `git merge-base HEAD origin/main` --- you'll get nothing since there
is no merge base in the current history

Increase the repo history
1. `git fetch --unshallow`
2. `git merge-base HEAD origin/main`
```
0a6e509af3
```
## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

Co-authored-by: Bolaji Olajide <bolaji.olajide@sourcegraph.com>
2024-08-08 14:13:07 +00:00
Erik Seliger
221b7f0fb6
tenant: Ensure tenant table also exists in codeintel and codeinsights DBs (#64359)
In some deployments, these are running in separate instances. This
migration makes sure that we can still reference the tenants from the
tenant_id column reliably everywhere.

It's critical that this migration is a noop on instances that already
have this table, so please double check me here during code review.

Test plan: Integration and E2E tests still pass, as this should be a
noop.
2024-08-08 15:33:49 +02:00
Stefan Hengl
c071a715cd
chore(backend): enable diskcache for multi-tenant (#64335)
Unless tenants are enforced, we use the old code path. If they are
enforced:
- zips are stored in `<cache-dir>/tenants/<tenantID>/<key>`
- evict runs globally

I also added another test helper to create tenants with fresh IDs for
every call

## Test plan:
- Updated unit tests
- Manual testing: I verified that unindexed symbol and text search work
and that a `/tenant/1` dir is created in both cache dirs
(`/tmp/searcher-archive` and `/tmp/symbols-cache`).
2024-08-08 13:18:34 +00:00
Erik Seliger
55cdb4961c
graphqlbackend: Move utils to internal/ (#64117)
The utils are currently used outside of cmd/frontend, so to break the
internal -> cmd import I'm moving and merging the utils package with
internal/gqlutil.

Test plan: Just moved around and renamed a package, the go compiler
doesn't complain.
2024-08-08 14:18:37 +02:00
Jean-Hadrien Chabran
2c73f72e85
chore(local): rename experiment single-program commandset (#64341)
Now that https://github.com/sourcegraph/sourcegraph/pull/64339 is
merged, we can tell users more about what to expect with `sg start
single-program-experimental-blame-sqs`. And as it's been in flight for a
while now, it's safe to say that's it's time to give it a shorter name
😊.

So it's been renamed from `single-program-experimental-blame-sqs` to
`minimal`. And to ensure nobody is getting confused, a `deprecated`
attribute has been added on the command sets, which is used here to
indicate that the new alternative is `sg start`.

 Thoughts about `sg start minimal`? `sg start single` perhaps? 

Running the old commandset: (ignore the yellow message, that's just a
local warning from `sg`)

![CleanShot 2024-08-07 at 17 37
31@2x](https://github.com/user-attachments/assets/a36afe54-7ccc-4437-b11b-ad288536c8da)

Running the new commandset, with the preamble explaining what to expect:

![CleanShot 2024-08-07 at 17 38
51@2x](https://github.com/user-attachments/assets/aa9af41a-8bad-48f5-ae46-68a357464bf5)

## Test plan

Locally tested.
2024-08-08 13:55:06 +02:00
Felix Kling
975b14f244
fix(svelte): Don't animate menu icon (#64358)
Fixes srch-858

Currently the menu icon rotates when hovering over it. The animation
should only target the Sourcegraph logo.

Additional changes:

- Move icon color style prop into CSS declaration (avoids inserting an
additional element)
- Let the animation target the link instead of the icon. There doesn't
seem to be reason why we actually need to target the `svg` element via
`:global`.


## Test plan

Manual testing.
2024-08-08 11:35:39 +00:00
Erik Seliger
1819daa7a7
tenant: Introduce tenant table to frontend database (#64322)
This PR adds a basic table for storing tenants in the database, and automatically inserts a tenant 1 for existing instances.

Test plan: Adds a new, not yet used table. The migration is very simple, so shouldn't cause any issues to existing instances.
2024-08-08 12:03:52 +02:00
Erik Seliger
f61ce6e8e8
tenant: Introduce first version of tenant package (#64271)
This PR aims to craft the /internal/tenant package for use by all Sourcegraph cluster-internal services to properly scope data visibility to the correct requesting tenant.
For now, we only expose methods we know we will DEFINITELY need.

This PR also adds the required middlewares so we can start to tinker with it in implementations.

## Test plan

CI passes. We don't enforce anything for now except not passing unparseable tenant IDs, which should be fine.
2024-08-08 12:02:19 +02:00
Felix Kling
1c729823d5
refactor(svelte): Improve integration with sg (#64333)
There currently isn't a 'one step' way to start a local Sourcegraph
instance with the SvelteKit app.

This commit adds `sg start enterprise-sveltekit` to fix that.

The changes in https://github.com/sourcegraph/sourcegraph/pull/64272
allow us to run the vite dev server in front of the Sourcegraph
instance, instead of building the assets and having them served by
frontend.
This gives us the benefit of hot module reloading and in general seems
to be a less fragile approach.

It's basically the same what we do with the React app in development
mode.

## Test plan

`sg start enterprise-sveltekit` starts the vite dev server as well as
the sourcegraph instance. Navigating to
`https://sourcegraph.test:3443/search` opens the Svelte app (when
enabled and logged in). Making a change in a source file updates the web
page immediately.

`sg start web-sveltekit-standalone` still works
2024-08-08 11:39:26 +02:00
Felix Kling
cf5467150b
fix(svelte): Improve hovercard UI for search based info (#64350)
I don't know why but having `overflow-x` causes the content of the
hovercard to not fully expand to the edges. It has something to do with
the sizing of the `hr` element.


## Test plan

Manual testing.
2024-08-08 09:36:49 +00:00
Erik Seliger
a3f23a5972
searcher: Consolidate FetchTar and FetchTarPaths (#64268)
There was a todo comment that said we want to consolidate them but didn't yet to keep another diff smaller - so now we're doing that.

Test plan: Integration tests for search still pass.
2024-08-08 11:04:38 +02:00
Erik Seliger
5a39f81d84
chore: Move cmd/frontend/backend to internal (#64261)
To prevent cross-cmd imports in the future, moving the backend package into internal.

Test plan: Just moved a package around, Go compiler doesn't complain and CI still passes.
2024-08-08 11:02:51 +02:00
Noah S-C
b9c4e2aae9
Revert "Revert "refactor: upgrade to rules_oci 2.0 (2nd attempt)"" (#64354)
Reverts sourcegraph/sourcegraph#64351

## Test plan

Need to test on main due to main-only CI steps (even with main dry-run)
2024-08-08 09:00:08 +00:00
Erik Seliger
db550f9618
auth: Remove redirects to session package (#64260)
These functions are not required to be called outside of frontend, so there's no need to reexport them. Instead, we consolidate the signout cookie logic in the session package.

Test plan: Just moved some code around, go compiler doesn't complain.
2024-08-08 10:40:53 +02:00
Greg Magolan
384959a6c8
fix(build): forward runfiles in custom oci_image_cross rule (#64353)
This should resolve the Workflows delivery failure seen in
https://buildkite.com/sourcegraph/sourcegraph/builds/286482#01912eb8-a1a9-48c6-81b0-4f5a09448bbb
after landing the rules_oci 2 upgrade:

```
  · Error: failed to compute runfiles hash for manifest: error concurrently hashing file /mnt/ephemeral/output/sourcegraph/__main__/execroot/__main__/bazel-out/k8-opt-ST-d57f47055a04/bin/dev/build-tracker/image_underlying/blobs/sha256/104f4630c01017c52e968bfe039f6eb7622ef1ad9d44d94d784cc9c39992961b: failed to open file /mnt/ephemeral/output/sourcegraph/__main__/execroot/__main__/bazel-out/k8-opt-ST-d57f47055a04/bin/dev/build-tracker/image_underlying/blobs/sha256/104f4630c01017c52e968bfe039f6eb7622ef1ad9d44d94d784cc9c39992961b for hashing: open /mnt/ephemeral/output/sourcegraph/__main__/execroot/__main__/bazel-out/k8-opt-ST-d57f47055a04/bin/dev/build-tracker/image_underlying/blobs/sha256/104f4630c01017c52e968bfe039f6eb7622ef1ad9d44d94d784cc9c39992961b: no such file or directory
```

The issue was that the runfiles of the underlying oci_image
(`image_underlying` target) were not being forwarded through the custom
`oci_image_cross` rule and therefor were not being built or fetched from
the remote cache and layed out on disk for the delivery step.

In this repo, the `oci_image` rule is a macro that is an underlying
`oci_image` with the main target being an `oci_image_cross`:

```
# Apply a transition on oci_image targets and their deps to apply a transition on platforms
# to build binaries for Linux when building on MacOS.
def oci_image(name, **kwargs):
    _oci_image(
        name = name + "_underlying",
        tars = kwargs.pop("tars", []) + ["//internal/version:stamps"],
        **kwargs
    )

    oci_image_cross(
        name = name,
        image = ":" + name + "_underlying",
        platform = select({
            "@platforms//os:macos": Label("@zig_sdk//platform:linux_amd64"),
            "//conditions:default": Label("@platforms//host"),
        }),
        visibility = kwargs.pop("visibility", ["//visibility:public"]),
    )
```

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-08 09:40:41 +01:00
Erik Seliger
8de09ddbc7
chore: Cleanup more cross-cmd imports (#64259)
This PR fixes a few more imports from /internal/ packages using /cmd/... contents.

Test plan: Mainly moved code around and CI still passes.
2024-08-08 10:10:58 +02:00
Erik Seliger
889ed1d948
oidc: Don't require to run refresh on provider init (#64159)
This PR makes the calls to create the OIDC provider explicit, so that we don't need to implicitly need to call a Refresh method, even if we might end up not needing the `p.oidc`.
This is a start toward being able to create providers on the fly cheaply vs having a globally managed list of providers in memory.

We did call refresh everywhere we do now anyways to the best of my understanding, so a passive goroutine in the background to my best understanding didn't add a lot here.

Test plan: Auth with SAMS locally still works.
2024-08-08 10:09:27 +02:00
Robert Lin
05e96ba1c4
fix/enterpriseportal/importer: disable query tracing when importing (#64352)
This can generate 10k+ spans in production

Also added simple handling for `pgx.NamedArgs` here, since I notice
those are missing

## Test plan

CI
2024-08-07 23:14:02 +00:00
Noah S-C
addba96f47
Revert "refactor: upgrade to rules_oci 2.0 (2nd attempt)" (#64351)
Reverts sourcegraph/sourcegraph#63829

Not working with Aspect Delivery

## Test plan

CI
2024-08-07 22:15:21 +00:00
Ara
3b16059588
Changing azureUseDeprecatedCompletionsAPIForOldModels to default to true (#64347)
Changing azureUseDeprecatedCompletionsAPIForOldModels to default to
trueso that customers who upgrade don't have to change siteadmin config
<img width="323" alt="image"
src="https://github.com/user-attachments/assets/a690b54b-aa43-43c3-9f7d-202f161866bc">



## Test plan

Tested locally 

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-07 23:43:01 +02:00
Greg Magolan
be015c58c2
refactor: upgrade to rules_oci 2.0 (2nd attempt) (#63829)
2nd attempt of #63111, a follow up
https://github.com/sourcegraph/sourcegraph/pull/63085

rules_oci 2.0 brings a lot of performance improvement around oci_image
and oci_pull, which will benefit Sourcegraph. It will also make RBE
faster and have less load on remote cache.

However, 2.0 makes some breaking changes like

- oci_tarball's default output is no longer a tarball
- oci_image no longer compresses layers that are uncompressed, somebody
has to make sure all `pkg_tar` targets have a `compression` attribute
set to compress it beforehand.
- there is no curl fallback, but this is fine for sourcegraph as it
already uses bazel 7.1.

I checked all targets that use oci_tarball as much as i could to make
sure nothing depends on the default tarball output of oci_tarball. there
was one target which used the default output which i put a TODO for
somebody else (somebody who is more on top of the repo) to tackle
**later**.

## Test plan

CI. Also run delivery on this PR (don't land those changes)

---------

Co-authored-by: Noah Santschi-Cooney <noah@santschi-cooney.ch>
2024-08-07 22:21:49 +01:00
Felix Kling
bcc816ac52
feat(svelte): Support 'got to defintion' for multiple definitions and 'find implementations' (#64349)
This commit adds the necessary logic to open the explorer tab for
multiple references and for implementations. I basically copied what
@camdencheek did for the references tab.


## Test plan

Hover over `adapt` in
http://localhost:5173/github.com/sveltejs/kit@65931f276ac2102032e3032c864a472eee19b7bb/-/blob/packages/kit/src/exports/vite/index.js?L890
and click 'got to definition'. The explore panel with should open with
the definitions tab selected.

I wasn't able to test the find implementations logic because I don't
know for which language we have this implemented.
2024-08-07 21:18:59 +00:00
Robert Lin
24ab5292bf
fix/enterpriseportal/importer: import all subscriptions (#64348)
Turns out, the `dev` tag is not a reliable indicator of whether a
license is for dev use only - let's just import all subscriptions into
prod, and drop the customer records from dev later.

## Test plan

CI
2024-08-07 21:08:07 +00:00
Robert Lin
72f88adc15
fix/enterpriseportal/importer: make generated display name more unique (#64346)
Several subscriptions, upon import, ran into conflicts even with the
username - user display name - date format.


https://sourcegraph.sentry.io/issues/5688073768/?referrer=slack&notification_uuid=83d264fb-364a-4bc1-a5ab-9d7164a906cd&alert_rule_id=15193465&alert_type=issue

## Test plan

unit tests
2024-08-07 20:24:52 +00:00
Robert Lin
eedc12e789
feat/enterpriseportal: import data from dotcom (#63858)
Adds a background job that can periodically import subscriptions,
licenses, and Cody Gateway access from dotcom.

Note that subscriptions and licenses cannot be deleted, so we don't need
to worry about that. Additionally licenses cannot be updated, so we only
need to worry about creation and revocation.

The importer can be configured with `DOTCOM_IMPORT_INTERVAL` - if zero,
the importer is disabled.

Closes https://linear.app/sourcegraph/issue/CORE-216
## Test plan

```
DOTCOM_IMPORT_INTERVAL=10s sg start dotcom
```

Look for `service.importer` logs. Play around in
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions/
to create and edit subscriptions, licenses, and Cody Gateway access.
Watch them show up in the database:

```
psql -d sourcegraph
sourcegraph# select * from enterprise_portal_susbscriptions;
sourcegraph# select * from enterprise_portal_susbscription_licenses;
sourcegraph# select * from enterprise_portal_cody_gateway_access;
```

---------

Co-authored-by: James Cotter <35706755+jac@users.noreply.github.com>
2024-08-07 11:44:18 -07:00
Felix Kling
5c9b7151cb
refactor(svelte): Optimize welcome overlay screenshot assets (#64344)
The screenshot images for the welcome overlay (both in Svelte and React)
are quite large.
In Svelte specifically, because they are implemented as Svelte
components, this adds a lot of code to the root layout and makes the
bundle quite large.

This commit converts the Svelte components to image files and passes
them (and the React ones) through [svgo](https://github.com/svg/svgo).

On one hand that makes the images much smaller, on the other hand in
Svelte the images are now independent of the JS code and can be loaded
separately (the React app was already using an `img` element).

Before svgo:

```
$ ls src/lib/assets/
total 3.1M
5.1K Aug  7 18:45 sourcegraph-logo.svg
1.5M Aug  7 18:46 welcome-screenshot-dark.svg
1.6M Aug  7 18:46 welcome-screenshot-light.svg
```

After svgo:

```
$ ls src/lib/assets/
total 1.4M
5.1K Aug  7 18:45 sourcegraph-logo.svg
667K Aug  7 18:50 welcome-screenshot-dark.svg
667K Aug  7 18:50 welcome-screenshot-light.svg
```

## Test plan

I temporarily changed the code so that the welcome dialog is always
shown in the Svelte app and inspected the image. It still seems to look
the same.
2024-08-07 17:37:27 +00:00
Jean-Hadrien Chabran
0fd6235fa4
chore(rel): prepare stitch graph for 5.6 (#64343)
The only manual action for bumping a minor but we'll get there :) 

## Test plan

CI
2024-08-07 19:25:15 +02:00
Jean-Hadrien Chabran
4591d989a6
chore(local): clear ambiguity in between sg version|live (#64122)
Context: As I was catching up with my Slack notifications, I spotted
this
[conversation](https://sourcegraph.slack.com/archives/C04MYFW01NV/p1721137862832899?thread_ts=1721136881.733869&cid=C04MYFW01NV)
and this PR is a 5m fix to avoid the problem to happen again.

What: If you haven't used `sg` in a while, it's easy to think that `sg
version` refers to the currently deployed Sourcegraph instance and not
the CLI. This commit adds a little preamble on stderr to not mess with
script usage while still reminding the user that it's the CLI version
that gets printed out.

Before: we printed the version without any context
After: we also print the following on stderr: `👉 Showing the current
version of the sg CLI, if you're looking for deployed Sourcegraph
instances version, please use `sg live` instead.`. Stderr so we don't
break things like `$(sg version)`.

Note: at a broader level, we should generalize this pattern, we don't
use too much `sg` raw output in scripts, but for the few places where
it's the case, it's a footgun.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Locally tested + CI. 

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

- `sg version` explicitly mentions that it's the CLI version that's
printed out, not any instance version.

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-07 18:34:38 +02:00
Camden Cheek
993e732583
Svelte: enable toggle by default (#64340) 2024-08-07 15:38:25 +00:00
Jean-Hadrien Chabran
9f0e1e04b8
chore(local): improve runnable cmds preambles in sg start (#64339)
`sg start ...` commands have a preamble field to inform the user about
various things. Prior to this PR, they were rather easy to miss. Along
the way, I've fixed the printing so if there multiple lines of preamble,
they appear nicely.

This PR addresses that. 


<details><summary>before/after</summary>
<p>
<img
src="https://github.com/user-attachments/assets/22d94ebb-e247-4e4e-8dab-1f502f1e8b46"/>
<img
src="https://github.com/user-attachments/assets/7cbbf41b-a926-4ebd-9f6d-bbdd779cc8b4"/>
</p>
</details> 

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

Locally tested, see before/after.
2024-08-07 15:20:07 +00:00
Camden Cheek
3ff0f07646
Svelte: more welcome banner behavior updates (#64311)
This makes some requested changes to the welcome banner. 

Notably:
- We no longer show the dialog unless the user switches into the svelte
version from react
- We don't show the dialog on every switch
- The dialog is accessible in the React via the "Learn more" button in
the menu
- Copy is updated to be less verbose
- The request for feedback is only shown once when switching out of the
svelte webapp
2024-08-07 08:55:57 -06:00
William Bezuidenhout
61b41814bd
fix(sg): provide suggestions we fail to get local gcp account email address (#64325)
Part of https://github.com/sourcegraph/devx-support/issues/1142

If we fail to get the gcp address, provide steps the user can try to fix
it

![Screenshot 2024-08-07 at 10 14
00](https://github.com/user-attachments/assets/39e6fdcb-ee60-43b8-bdca-d28a9d210b2e)


## Test plan
Tested locally

## Changelog
sg - provide steps a user can follow if we fail to get the local gcp
email address
2024-08-07 14:02:30 +00:00
Varun Gandhi
e1e78988aa
chore: Add docs for RepoStore methods (#64283) 2024-08-07 21:27:37 +08:00
Felix Kling
e4e1f55026
fix(svelte): Properly redirect to cody marketing page (#64331)
Fixes srch-851

A consequence of https://github.com/sourcegraph/sourcegraph/pull/64272
is that redirecting to the cody marketing page on dotcom didn't work.
That's because `/cody` is not provided by the server as a known page.

A simple fix would be to mark the link as external, but we'd have to
keep in mind to do this in all places (present and future).

A more "central" fix is to add this page to a hardcoded list of known
pages that are not provided by the server.


## Test plan

Manual testing
2024-08-07 15:24:02 +02:00
Felix Kling
2e0a3ee92e
fix(svelte): Better preloading in file tree (#64327)
Currently the link element doesn't extend to the full width of the
sidebar. You can click outside of the actual text to navigate to the
file, but it won't be preloaded.

Now the link occupies the full width.

## Test plan

Manual testing.
2024-08-07 15:23:35 +02:00
Quinn Slack
f7d4517dbc
upgrade Cody Web, always create a new chat (#64334)
Incorporates https://github.com/sourcegraph/cody/pull/5129

## Test plan

Run in SvelteKit and non-SvelteKit. Ensure that the Cody standalone chat
and Cody sidebar chats work.
2024-08-07 13:23:25 +00:00
Felix Kling
ebaab129ee
feat(svelte): Add support for creating search jobs from search results (#64308)
Closes srch-838

This commit extends the search progress popover and adds the search jobs
section.

In the React version the UI for the popover differs slightly when search
jobs are enabled vs not enabled.

I decided to ignore the differences and only impolemented the style used
for the 'search jobs enabled' version, which makes the popover a bit
more compact.

The logic for validating and creating a search job is encapsulated in a
class which makes it easy to conditionally show the search jobs UI.

Additional changes:

- Skipped items is now a list and uses `<details>` elements which is
semantically more correct. We loose the styling of the chevron but I
think that's OK.
- LoadingSpinner was updated to work inline.
- Logging was fixed (?) in the React version to send the correct
meta-data.
- Added integration tests for the search job popover behavior

## Test plan

Integration tests and manual testing.
2024-08-07 14:25:35 +02:00
Varun Gandhi
93818e0d9b
fix: Try workaround for bad index choice when updating execution logs (#64328)
Under high contention, the updating of execution logs query:

```
UPDATE
  lsif_indexes
SET
  execution_logs = execution_logs || $1::json
WHERE
  id = $2
  AND worker_hostname = $3
  AND state = $4 RETURNING ARRAY_LENGTH(execution_logs, $5)
```

Was taking multiple seconds due to lock contention on the
lsif_indexes_state index.

![image](https://github.com/user-attachments/assets/be58bc97-0995-4909-a032-69084ad995c5)

Running `EXPLAIN ANALYZE` on Sourcegraph.com under lower contention uses
the primary key index on id, so we don't have an easy way to test the
high contention scenario. Try this alternate query form to see if that fixes the issue.
2024-08-07 13:22:15 +02:00
Michael Bahr
4d6e8949e8
fix(batches): don't request unnecessary info that's likely to cause GH errors (#64299)
Closes SRCH-802

After a long and unsuccessful hunt of eventual consistency errors, I
noticed that we don't need the GraphQL fragments that are causing
problems.

I introduced a simplified request, which succeeds reliably. What
customers should see now is one error (see second picture below), which
is followed by a retry, and then success.

Previously we've seen this error, sometimes less often, sometimes more,
but customers saw it so often that it caused their batch changes to
fail.

<img width="1042" alt="Screenshot 2024-08-06 at 14 02 00"
src="https://github.com/user-attachments/assets/c5a099da-d474-43db-ac12-ac7c4f22d4d3">

Customers may still see an initial error, which I've seen to reliably
disappear on the first retry. It should not be a problem

<img width="1039" alt="Screenshot 2024-08-06 at 14 02 48"
src="https://github.com/user-attachments/assets/99f278d4-4020-48ea-b4ac-32cbdfce455d">

## Test plan

Manual testing

## Changelog

- fix(batches): improve GitHub Apps integration reliability by
simplifying the data requested from GitHub
2024-08-07 10:47:37 +02:00
Christoph Hegemann
81fa144f4f
refactor: steps the usage cursor provenance state in a single place (#64321)
Adds a second function to determine the initial cursor based on the
requested provenances.

## Test plan
N/A
2024-08-07 10:39:12 +02:00
Naman Kumar
3efa77aad9
Center align Cody logo in Cody Web Sidebar (#64324)
Fixes Cody Logo alignment to center for both React & Svelte Cody Sidebar
header.

## Test plan

Before:
![CleanShot 2024-08-07 at 13 30
04@2x](https://github.com/user-attachments/assets/c1b8471d-3f25-4b75-bf54-888876578d63)

After:

![CleanShot 2024-08-07 at 13 30
19@2x](https://github.com/user-attachments/assets/483e1abd-ea6e-498b-8d98-6295a23f5cca)

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-07 09:21:57 +01:00
Christoph Hegemann
780b5dbbc4
chore: Move and clean up test code for syntactic usages (#64318)
Consolidates the two test helper/util modules, and moves one test file
to align with the file it's actually testing.

## Test plan

Tests continue to pass
2024-08-07 09:15:58 +01:00
Varun Gandhi
930033ca9b
chore: Replace QueuedCount -> CountByState with bitset parameter (#64302)
Previously, the QueuedCount method was confusing because:

1. By default, it actually returned the count for both the 'queued' and
   'errored' states (despite the name just have 'Queued').
2. There was an additional boolean flag for also returning entries in
    the 'processing' state, but reduced clarity at call-sites.

So I've changed the method to take a bitset instead, mirroring the
just-added Exists API, and renamed the method to a more
generic 'CountByState'.

While this does make call-sites a bit more verbose, I think the
clarity win makes the change an overall positive one.
2024-08-07 16:09:18 +08:00
Naman Kumar
6ee444656c
Fix Cody Web Svelte Sidebar (#64320)
Cody's Web Sidebar in Svelte is not following the theme when tested
locally.

This PR fixes that. I have tested this with multiple builds both with &
without the diff.

## Test plan

Before:

![image](https://github.com/user-attachments/assets/b2c669fa-a0a7-4dc7-9440-8fca7aa69fd5)

After:
![CleanShot 2024-08-07 at 12 20
19@2x](https://github.com/user-attachments/assets/66bda613-d811-47d0-b0c5-23707e60f875)


## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-07 07:27:23 +00:00
Christoph Hegemann
f1d5d779c3
refactor: handles Cursor uniformly over all usage provenances (#64319)
This change should not change any behaviour, but it prepares for syntactic/search-based pagination.

Both syntactic and search based usages now return a "NextCursor", which is `Some` if there are more results of their provenance to be had. For now they always return `None` which preserves the current behaviour. The logic in `root_resolver` implements a state machine that transitions the cursor through the provenances and makes sure to skip provenances if the cursor in the request starts a certain state.

## Test plan

Tests continue to pass, no behavioral changes
2024-08-07 08:26:31 +02:00
Naman Kumar
3680503eab
Update Cody Web to 0.3.7 (#64296)
closes:
https://linear.app/sourcegraph/issue/SRCH-821/context-is-not-being-fetched-on-vs-code-even-though-its-being-fetched

![CleanShot 2024-08-06 at 16 13
05@2x](https://github.com/user-attachments/assets/e338865c-5949-4b18-8e2c-41afcc4abc1b)

This PR updates Cody Web to 0.3.7. The latest version introduces the
following changes:
- Removes the Cody history panel and rather uses the tabs. (As updated
in latest version on Cody Web)
- Removes the `experimental.noodle` flag set to true. 
- Fixes the issue where the query for `getCodyContext` contained mention
chips text and was different from VS Code.

## Test plan

- visit /cody/chat

## Changelog
2024-08-07 10:27:17 +05:30
Bolaji Olajide
2e642bc85e
fix(bazel): surface error message when gazelle cant process glob expression (#64214)
Closes DINF-89

Gazelle sometimes have trouble processing glob expressions, and this
isn't reported as a failure even though it ultimately results in the
`BUILD.bazel` not being correctly updated.

## Test plan

* Manual testing

In `client/web/BUILD.bazel`, add a new `src` to the `web_lib` ts_project
target that includes a glob pattern.

```
...
ts_project(
    name = "web_lib",
    srcs = glob(["!src/playwright/*.spec.ts"]) + [
        "src/Index.tsx",
        "src/LegacyLayout.tsx",
        "src/LegacyRouteContext.tsx",
        "src/LegacySourcegraphWebApp.tsx",
        "src/PageError.tsx",
        "src/SearchQueryStateObserver.tsx",
        "src/SourcegraphWebApp.tsx",
...
```

When you run `go run ./dev/sg bazel configure`, the command should fail
with an error message instead of returning exit 0.

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Jean-Hadrien Chabran <jean-hadrien.chabran@sourcegraph.com>
2024-08-06 17:37:15 -05:00
Bolaji Olajide
4a5e1e450a
feat(sg): report user os information via analytics (#64280)
Closes DINF-193

![CleanShot 2024-08-05 at 21 28
37@2x](https://github.com/user-attachments/assets/34f121c5-5a85-456c-b12b-2f959573fcae)

OS information is now part of the `sg` analytics metadata.


## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

Any `sg` operation now reports the os information.

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-06 17:31:50 -05:00
Felix Kling
02fb199189
chore(svelte): Add manual entries for repo sub pages to development proxy (#64313)
I noticed that non-svelte repo subpages haven't been redirected to the
React app in local development (it works as expected in production).

That's because the proxy doesn't know about them since they are not part
of `knownRoutes`.
We could update the server code to include those routes as well but that
seems heavey handed just to make local development work.

I think in this case it's fine to have manual entries for the handful of
repo subpages that have not been migrated to Svelte yet.

## Test plan

Manual testing.
2024-08-06 15:46:33 -06:00
Felix Kling
b6a25c8a11
fix(own): Prevent infinite UI update loop in own pages (#64312)
I noticed that my computer fans kept on spinning when visiting
https://sourcegraph.test:3443/github.com/sourcegraph/sourcegraph/-/own
and
https://sourcegraph.test:3443/github.com/sourcegraph/sourcegraph/-/own/edit.

Long story short because we are not memoizing the breadcrumbs we are in
an infinite update loop. The offending commit is
c42c57da1d.

## Test plan

Manual testing. Fans stopped spinning.
2024-08-06 22:34:05 +02:00
Chris Smith
582022d301
Return model IDs from GraphQL, not model Names (#64307)
::sigh:: the problem here is super in the weeds, but ultimately this
fixes a problem introduced when using AWS Bedrock and Sourcegraph
instances using the older style "completions" config.

## The problem

AWS Bedrock has some LLM model names that contain a colon, e.g.
`anthropic.claude-3-opus-20240229-v1:0`. Cody clients connecting to
Sourcegraph instances using the older style "completions" config will
obtain the available LLM models by using GraphGL.

So the Cody client would see that the chat model is
`anthropic.claude-3-opus-20240229-v1:0`.

However, under the hood, the Sourcegraph instance will convert the site
config into the newer `modelconfig` format. And during that conversion,
we use a _different value_ for the **model ID** than what is in the site
config. (The **model name** is what is sent to the LLM API, and is
unmodified. The model ID is a stable, unique identifier but is sanitized
so that it adheres to naming rules.)

Because of this, we have a problem.

When the Cody client makes a request to the HTTP completions API with
the model name of `anthropic.claude-3-opus-20240229-v1:0` or
`anthropic/anthropic.claude-3-opus-20240229-v1:0` it fails. Because
there is no model with ID `...v1:0`. (We only have the sanitized
version, `...v1_0`.)

## The fix

There were a few ways we could fix this, but this goes with just having
the GraphQL component return the model ID instead of the model name. So
that when the Cody client passes that model ID to the completions API,
everything works as it should.

And, practically speaking, for 99.9% of cases, the model name and model
ID will be identical. We only strip out non-URL safe characters and
colons, which usually aren't used in model names.

## Potential bugs

With this fix however, there is a specific combination of { client,
server, and model name } where things could in theory break.
Specifically:

Client | Server | Modelname | Works |
--- | --- | --- | --- | 
unaware-of-modelconfig | not-using-modelconfig | standard | 🟢 [1] |
aware-of-modelconfig | not-using-modelconfig | standard | 🟢 [1] |
unaware-of-modelconfig | using-modelconfig | standard | 🟢 [1] |
aware-of-modelconfig | using-modelconfig | standard | 🟢  [3] |
unaware-of-modelconfig | not-using-modelconfig | non-standard | 🔴 [2] |
aware-of-modelconfig | not-using-modelconfig | non-standard | 🔴 [2] |
unaware-of-modelconfig | using-modelconfig | non-standard | 🔴 [2] |
aware-of-modelconfig | using-modelconfig | non-standard | 🟢  [3] |

1. If the model name is something that doesn't require sanitization,
there is no problem. The model ID will be the same as the model name,
and things will work like they do today.
2. If the model name gets sanitized, then IFF the Cody client were to
make a decision based on that exact model name, it wouldn't work.
Because it would receive the sanitized name, and not the real one. As
long as the Cody client is only passing that model name onto the
Sourcegraph backend which will recognize the sanitized model name / ID,
all is well.
3. If the client and server are new, and using model config, then this
shouldn't be a problem because the client would use a different API to
fetch the Sourcegraph instance's supported models. And within the
client, natively refer to the model ID instead of the model name.

Fixes
[PRIME-464](https://linear.app/sourcegraph/issue/PRIME-464/aws-bedrock-x-completions-config-does-not-work-if-model-name-has-a).

## Test plan

Added some unit tests.



## Changelog

NA
2024-08-06 13:28:33 -07:00
Felix Kling
c414477bee
fix(svelte): Center file tree loading indicator (#64309)
We should probably redesign the whole loading state but this simple
change is still better than the current behavior.

| Before | After |
|--------|--------|
|
![2024-08-06_21-00_1](https://github.com/user-attachments/assets/015d47d3-9542-4d72-b422-56975723576c)
|
![2024-08-06_21-00](https://github.com/user-attachments/assets/0e667bc2-496e-4169-806d-b49757681673)
|

## Test plan

Manual testing.
2024-08-06 21:20:49 +02:00
Chris Smith
b0bb67b47c
Update the default Sourcegraph-supplied LLM models (#64281)
This PR sets the defaults for "Sourcegraph supplied LLM models". 

## When will these "defaults" be used?

These models will _only_ be used IFF the Sourcegraph instance is
_explicitly_ using the newer "modelConfiguration" site configuration
data. (And opts into using Sourcegraph-supplied LLM models.)

If the Sourcegraph instance is using the older "completions"
configuration blob, then _only_ the user-supplied models will be used.
(Or, based on the specific defaults defined in the code for the
completions provider.)

## What about Cody Free or Cody Pro?

😬 yeah, we're going to need to deal with that later. Currently
Sourcegraph.com is _not_ using the newer "modelConfiguration" site
configuration, and instead we have some hacks in the code to ignore the
internal modelconfig. See this "super-shady hack":

e5178a6bc0/cmd/frontend/internal/httpapi/completions/get_model.go (L425-L455)

So we are just erring on the side of having Cody Free / Cody Pro "do
whatever they do now", and this PR won't have any impact on that.

We _do_ want Sourcegraph.com to only return this data, but there are a
few things we need to get straightened out first. (e.g. Cody Gateway
being ware of mrefs, and having Cody Clients no longer using `dotcom.ts`
to hard-code Cody Pro LLM models.)

## What does this PR actually _do_?

1. It updates the code in `cmd/cody-gateway-config` so that it will
produce a new "supported-models.json" file.
2. I then ran the tool manually, the output of which was then written to
`internal/modelconfig/embedded/models.json`.
3. That's it.

For any Sourcegraph releases after this PR gets merged, the "Sourcegraph
supplied LLM models" will be the newer set defined in `models.json`.
(i.e. having these new defaults, and including
"fireworks::v1::starcoder".)

## Test plan

~~I tested things locally, and unfortunately it doesn't look like any
clients are filtering based on the model capabilities. So "StarCoder" is
showing up in the Cody Web UI, despite failing at runtime.~~

Update: This was a problem on my end. This isn't an issue.


## Changelog

NA?
2024-08-06 10:26:56 -07:00
Stefan Hengl
ee93777dd4
fix(search_jobs): fail validation for repo searches (#64300)
This closes a pretty big gap in the query validation for Search Jobs. We
don't support repo search yet and searcher returned errors during
execution, complaining about missing patterns. With this PR we fail
during validation so users cannot even create these kinds of jobs. See
new test cases.

## Test plan
Updated unit tests
2024-08-06 17:16:52 +02:00
Varun Gandhi
bf4eb26bdf
fix: Add Exists method to dbworker Store to avoid COUNT(*) (#64297)
Running `COUNT(*)` on hot tables like lsif_indexes on Sourcegraph.com
shows up on profiles when the number of executors is bumped to
30+, and when the table has 100K+ jobs. So avoid `COUNT(*)`
where possible.
2024-08-06 22:13:09 +08:00
Varun Gandhi
99f7d97dc6
chore: Switch over to fake RepoStore in codenav tests (#64284)
Reduce the exposed surface area with a smaller interface
minimalRepoStore, and make sure we're using fakes in the
tests which better document the intent, instead of using a
mock repo store. The fake makes sure that the methods
are mutually consistent, which is easier to do when working
with a smaller interface.
2024-08-06 22:09:43 +08:00
Petri-Johan Last
1cac35b246
Update wolfi hashes (#64289)
Ran `sg wolfi update-hashes`

## Test plan

Hashes updated.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: William Bezuidenhout <william.bezuidenhout@sourcegraph.com>
2024-08-06 15:54:02 +02:00
Felix Kling
0959fbda1a
fix(svelte): Make /cody/dashboard work with the new web app (#64295)
Fixes srch-765

When navigating to `/cody/dashboard` and the new web app is enabled, the
user gets a "Not found" error. This doesn't happen in the React app.

The page doesn't exist in the new web app, hence the server should fall
back to the old web app but that doesn't happen.

Why? Because the server doesn't know about `/cody/dashboard` either. It
only exists in the React app.
Instead the server interprets this path as a (non-existing) repository
page. When the new web app is enabled, repository pages are handled by
the new web app, but since neither the repo nor the page exist in the
new web app, the aforementioned error is thrown.

Configuring this route on the server makes it so that the React app is
served instead.

## Test plan

Manual testing. Going to https://sourcegraph.test:3443/cody/dashboard
loads the React app.
2024-08-06 15:33:24 +02:00
Julie Tibshirani
958afb0936
Search: boost matches on quoted terms (#64298)
Follow up to #64207. In our old search semantics, quotes were
interpreted literally. So a query like `"sourcegraph"` would match only
strings like `fmt.Println("sourcegraph")`. Now, both single and double
quotes are used for escaping, and mean that the contents should be
searched exactly.

This PR makes sure to boost matches on quoted terms in result ranking.
This way, users familiar with the old syntax are more likely to find
what they're after.

## Test plan

Adapted unit tests. Re-tested all queries from #64207 manually, plus
these ones:
* `'sourcegraph'`
* `"sourcegraph"`
2024-08-06 15:55:24 +03:00
Erik Seliger
ff52b14dd1
chore: Remove unnecessary _ imports (#64158)
These imports don't seem to have side-effects so dropping them to keep the dependency graph simple.

Test plan: E2E CI still passes.
2024-08-06 13:28:29 +02:00
Erik Seliger
6b98c253ab
chore: Frontend does not need disk (#64273)
A long time ago, we dropped the requirement for frontend to have any
disk for caching. Our helm deployments use read-only rootFSes, so this
wouldn't even work.

This PR aims to make that clearer by removing some last remnants of
those times.

Test plan: Frontend starts locally and integration tests pass in CI.
2024-08-06 13:22:00 +02:00
Julie Tibshirani
f19af57fe4
Search: re-add support for 'lucky' patterntype (#64293)
In #64215, we removed support for smart search. We continued to allow
the `smart` search mode, but just execute with `precise` behavior.
However, we started to throw an error for `patterntype:lucky` (which is
the old way of specifying smart search). It turns out that `lucky` made
its way into some search links and settings, causing those searches to
fail.

This PR restores support for `lucky`, and remaps it to `standard`. This
preserves the semantics as much as possible (since smart search attempts
a 'standard' search as its first rule).

Closes SRCH-840
2024-08-06 14:04:09 +03:00
Varun Gandhi
8f058838ce
chore: Consolidate mocks for dbworker/store.Store type (#64294)
Let's not regenerate it 4 extra times -- it's already generated
once in a central dbworker/store/mocks package which we can reuse.
2024-08-06 18:40:25 +08:00
Felix Kling
e4a8ce52da
fix(svelte): Update top-level route list (#64272)
tl;dr: Everything is derived from `window.context.svelteKit.knownRoutes`

*buckle up*

### Context

After the new web app was enabled by default on dotcom I looked at
dotcom data in Sentry to see if there was anything out of the ordinary.
I noticed a high number of errors related to resolving repository
information. The most common non-existing repository that was reported
was `-/sign-out`.

Of course this shouldn't happen. `/-/sign-out` is the sign out URL and
shouldn't be interpreted as a repository.

Currently we prevent SvelteKit from interpreting specific paths as
repositories by using the `reporev` parameter validator:

```ts
// src/params/reporev.ts
const topLevelPaths = [
    'insights',
    'search-jobs',
    'saved-searches',
    // ... many more here
]

const topLevelPathRegex = new RegExp(`^(${topLevelPaths.join('|')})($|/)`)

// This ensures that we never consider paths containing /-/ and pointing
// to non-existing pages as repo name
export const match: ParamMatcher = param => {
    // Note: param doesn't have a leading slash
    return !topLevelPathRegex.test(param) && !param.includes('/-/')
}
```

`-/sign-out` was not in that list, including others which have been
added since this file was originally created.

Adding it would have been the simple solution but having to maintain
this list manually has always irked me. Now we have a better way...

### Production changes

#### Client side

It turns out we are already sending a list of known routes to the client
in `window.context.svelteKit.knownRoutes` to basically do the same
thing: test whether a given path is a page or a repository.

```ts
// src/lib/navigation.ts
let knownRoutesRegex: RegExp | undefined

function getKnownRoutesRegex(): RegExp {
    if (!knownRoutesRegex) {
        knownRoutesRegex = new RegExp(`(${window.context?.svelteKit?.knownRoutes?.join(')|(')})`)
    }
    return knownRoutesRegex
}

// ...

export function isRouteEnabled(pathname: string): boolean {
    let foundRoute: SvelteKitRoute | undefined
 
    // [...]

    if (foundRoute) {
        if (foundRoute.isRepoRoot) {
            // Check known routes to see if there is a more specific route than the repo root.
            // If yes then we should load the React app (if the more specific route was enabled
            // it would have been found above).
            return !getKnownRoutesRegex().test(pathname)
        }
        return true
    }

    return false
}
```

Why do we have the `reporev` validator and `isRouteEnabled`? They
basically do the same thing (check whether a path is a known page or a
repository) the first (`reporev`) is used by SvelteKit to determine
which route a path corresponds to (i.e. to navigate to the repository
page or whether the page doesn't exist) and the second one
(`isRouteEnabled`) is used after the route resolution but before route
loading. It's used to trigger a full page refresh to fetch the React
version if necessary.

Anyways, since we already have a list of known pages from the server,
the parameter validator should just use it too. Except it didn't work,
which made the following server side changes necessary.

#### Server

We register routes in multiple places. Right now `knownRoutes` is
populated from the router created in
`cmd/frontend/internal/app/ui/router.go`, but this does not include
`/-/sign-out`. This route (and others) are defined in
`cmd/frontend/internal/app/router/router.go` (I don't know what the
difference is). I extended the sveltekit route registration code so
that's possible to register routes from multiple routers.

I couldn't test it yet however because I currently can't get Sourcegraph
to run locally (Camden tested it; it works).

### Development mode changes

After the above changes, navigating to a React only page in development,
e.g. `/insights` would show a 'repo not found error' because
`window.context.svelteKit.knownRoutes` was empty in development. So
every non-existing page would be interpreted as missing repository.

Hardcoding a list of known pages *again* just for development seemed to
be a step backwards. So I spent quite a bit of time to find a way to
extract the JS context object from the HTML page returned by the origin
server and inject it into the HTML page generated by SvelteKit, similar
to how we do it for the React app.

Additionally the value of `window.context.svelteKit.knownRoutes` is now
used to setup the proxy to non-supported pages from the server, so we
don't have to maintain this regex anymore either:

```ts
 // Proxy requests to specific endpoints to a real Sourcegraph
 // instance.
 '^(/sign-(in|out)|/.assets|/-|/.api|/.auth|/search/stream|/users|/notebooks|/insights|/batch-changes|/contexts)|/-/(raw|own|code-graph|batch-changes|settings)(/|$)': { ... }
```

This means that requesting non-svelte pages will also return the
corresponding React version in development.


## Test plan

Manual testing.
2024-08-06 09:53:50 +00:00
Christoph Hegemann
4ebb805bd3
fix: uses the same base64 for decoding we use for encoding the UsageCursor (#64290)
At the moment we decode via the "Std" encoding, which expects padding
but we encode with "Raw" which doesn't add any.

## Test plan

Manual testing
2024-08-06 17:38:00 +08:00
Keegan Carruthers-Smith
c09552ed15
searcher: fix benchmarks (#64292)
Column helper now returns 0 based indexes. FilterTar became a required
function on diskcache.

Test Plan: go test -run '^$' -bench . ./cmd/searcher/internal/search

Fixes
https://linear.app/sourcegraph/issue/SPLF-183/benchmarks-in-searcher-broken
2024-08-06 11:33:52 +02:00
Stefan Hengl
155975259a
fix(search_jobs): progress reporting (#64287)
Relates to #64186

With this PR we only show `83 out of 120 tasks` if the search job is
currently processing. In all other states, we don't show this stat. This
is a consequence of the janitor job I recently added, because after
aggregation, this data is not available anymore. User's can still
inspect the logs and download results to get a detailed view of which
revisions were searched.

I also remove an unnecessary dependency of the download links on the job
state.

## Test plan:

I ran a search job locally and confirmed that the progress message is
only visible while the job is processing and that logs and downloads are
always available.

## Changelog
- Show detailed progress only while job is in status "processing"
- Remove dependency of download links on job state
2024-08-06 11:16:04 +02:00
Varun Gandhi
38633daef0
chore: Consolidate mocks for uploads's Store type (#64286)
Instead of re-generating and re-compiling the mocks 3 times,
consolidate them into a single storemocks package.

This should also provide better code navigation in the editor.
2024-08-06 10:15:17 +01:00
Varun Gandhi
224e23697d
chore: Reduce frequency of COUNT(*) on lsif_indexes (#64288)
Previously, for metrics reporting, we were querying the number of
queued+errored records every 5 seconds. For large queues +
heavy contention, this scan itself takes a few seconds, despite using
an index. Reduce the frequency of this scan as we
don't need updates to the queue size every 5 seconds.

## Test plan

Check that frequency of `COUNT(*)` is reduced on Sourcegraph.com once
this patch makes its way to Sourcegraph.com
2024-08-06 10:39:20 +02:00
Christoph Hegemann
e48368df53
Enable SCIP based APIs by default (#64285)
Closes
https://linear.app/sourcegraph/issue/GRAPH-784/default-scip-api-ff-to-on

Enable SCIP based APIs by default, as they're required for the web app
refresh.

## Test plan
Things have been going fine on Dotcom and S2
2024-08-06 06:12:30 +00:00
Stefan Hengl
737e460a64
chore(search): update logging of search durations (#64269)
The current logging is outdated. This PR is not a complete rewrite. It
tries to keep semantics mostly as-is but it is more generous when it
comes to what we log. (For example we didn't log `(AND foo bar)` before)

IMO this is a good compromise we can ship quickly and then take some
time to figure out how to distinguish suggestions, searches, code-intel
and whether it is a good idea to mix search types and result types.

Updates:
- Prefer to log result types, fall back to pattern type. (This is
largely the same logic as before but we don't bail for complex queries)
- Don't guess repo and file results types if not explicitly specified.
We loose a bit of information here but it keeps the code much cleaner.
- Allow "AND" and "OR" operators.

The updated test case gives a good overview of how we would log things
in the future.

Kept as-is:
- I left "new" and "legacy" logging in place. I am not sure how we use
the target stores right now so I wanted to keep this as-is for now.
However we should see if we can retire the legacy logging.
- The previous and current logic translates `type:file` queries to
pattern types. I guess this makes sense from the perspective of how
things are implemented in the backend.
- "type:path" is logged as "file".

## Test plan:
Updated unit test
2024-08-06 07:26:01 +02:00
Chris Smith
a310035006
Return 'sourcegraph' as the CodyLLMConfigurationResolver.Provider (#64276)
This PR fixes Cody autocomplete in some situations, fixing
[PRIME-426](https://linear.app/sourcegraph/issue/PRIME-426/autocomplete-completely-broken-in-main-with-and-sometimes-without-the).

Our story begins with this PR:
https://github.com/sourcegraph/sourcegraph/pull/63886. The PR updated
the `CodyLLMConfigurationResolver.Provider` GraphQL endpoint to no
longer return the "provider" that was put into the site configuration,
but to instead return the _display name_ of the provider, or if multiple
were configured the string "various".

```diff
- func (c *codyLLMConfigurationResolver) Provider() string {
- 	return string(c.config.Provider)
- }
+ func (c *codyLLMConfigurationResolver) Provider() string {
+	if len(r.modelconfig.Providers) != 1 {
+		return "various"
+	}
+	return r.modelconfig.Providers[0].DisplayName
+}
```

This change was wrong on several levels, and unfortunately stemmed from
the original author (me) not tracking down and understanding how the
GraphQL endpoint was actually used.

Once we discovered the problem, we quickly rectified this by changing
the behavior to the more correct version of returning the Provider ID of
the code completion model with
https://github.com/sourcegraph/sourcegraph/pull/64165:

```go
func (r *codyLLMConfigurationResolver) Provider() string {
	return string(r.modelconfig.DefaultModels.CodeCompletion.ProviderID())
}
```

However, after some more testing we discovered yet another edge case. We
didn't realize that the provider "sourcegraph" (which is how you
configure Sourcegraph to use Cody Gateway, using the older site config
method) was required in some scenarios on the Cody client.

So the new logic, of returning the Provider ID was incorrect. (Because
we report the _model_ provider, e.g. "anthropic". Not the _API_
provider, e.g. "sourcegraph"/"Cody Gateway".)

With this change, we should just have the behavior we had initially:
returning whatever the admin had configured in the
"completions.provider" section of the site config. If only the newer
modelconfig settings were used, we return "sourcegraph" if using Cody
Gatway. And if not, just return the Provider ID. (Though in some
situations even that will lead to incorrect results, because ultimately
we need to update the client here.)

## Test plan

I wasn't able to test this super-well manually, and am relying on
Stephen and Taras' knowledge of how the client uses this today.

## Changelog

NA
2024-08-05 19:15:11 -07:00
Ara
e0991a68ea
Improving Azure errors for customer containers (#64278)
Fixing the logging description for Containers

## Test plan
Tested locally with containers

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-06 01:19:09 +00:00
Jacob Pleiness
44869b9a5c
appliance(chore): Remove legacy maintenance API (#64282)
Appliance now uses the API defined in internal/appliance. Deleted files
were no longer uses and an artifact from porting code from the POC.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Unit tests covering API are already in place.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-05 20:49:55 -04:00
Camden Cheek
b9823cc90b
Svelte: remove site admin gate on code intel preview (#64277)
When I added this, for some reason I thought it was site admin only. As
it turns out, it shouldn't be gated to site admins only, and it makes it
particularly annoying on dotcom.
2024-08-05 23:59:15 +00:00
Jason Hawk Harris
e5178a6bc0
Revert "[Svelte]: UI Updates for Perforce Depots and Git Repos" (#64275)
Reverts sourcegraph/sourcegraph#64014

We decided that including this in the August 7th release would be rushed
after diving deeper into the project. Reverting this in order to
re-write the functionality, especially the data loading components.

## Test Plan
- this is a revert PR. Everything will work as before.
2024-08-05 16:30:41 +00:00
Felix Kling
4e5ea2a082
refactor(svelte): Reduce logo complexity (#64274)
There is no need to have a separate image file for dark mode. The SVG
file can handle color switching itself.


## Test plan

Switched theme in the user menu and in the browser dev tools.
2024-08-05 18:19:32 +02:00
Camden Cheek
44d8512779
Svelte: make closing the welcome overlay more obvious (#64256)
In response to [this
request](https://sourcegraph.slack.com/archives/C05MW2TMYAV/p1722633022111559),
I modified the welcome banner to:
- Add a close button in the top right
- Close on click outside the banner
- Make the button primary rather than secondary
2024-08-05 08:51:40 -06:00
Erik Seliger
765a8cdaf1
chore: Move cmd/frontend/webhooks to cmd/frontend/internal (#64157)
Nothing outside frontend needs to import this package, to properly signify that we move it to internal where 90% of the other packages reside, and avoid ambiguity on "what service is running what code exactly".

Test plan: Just moved a package, Go compiler doesn't complain.
2024-08-05 16:46:38 +02:00
Erik Seliger
d8fb5aeb21
frontend: Consolidate remaining registry packages (#64156)
This PR simplifies and consolidates the remaining parts of the various registry packages, and moves everything under cmd/frontend/internal for better encapusation.
This also removes the need to _ import packages which feels very brittle.

Test plan: Go compiler doesn't complain about moved code.
2024-08-05 16:29:50 +02:00
Erik Seliger
3fd5abc292
frontend: Remove global conf server variable (#64155)
To make things more explicit and remove the global variable, this is now passed down to where it's needed.
It is a bit messy right now, since it's used deep in the serve-handler but that just highlights better where
it's actually used IMO. As a next step, I want to get rid of the requirement to indicate server-restart
required, so we should be able to drop a bunch of the prop drilling here.

Test plan: Still compiles, E2E test works.
2024-08-05 16:28:39 +02:00
Petri-Johan Last
f4116695a6
Update p4-fusion-sg wolfi-package (#64266) 2024-08-05 15:00:09 +02:00
Varun Gandhi
e5fdb5c3fc
fix: Fixes incorrect highlighting for comments at the start of a file (#64235)
The problem was that we were incorrectly not doing
a "stack push" operation when encountering a comment,
but we were doing a pop which triggered a change in the
source range for the next source range (this is done to
avoid overlap between the current occurrence and the
subsequent occurrence that will be emitted).

This is fixed by not ignoring comment markers. As a consequence, we will
emit a few more occurrences than earlier, but I don't think it should be a
big problem in practice. We can also fuse these if needed.
2024-08-05 20:58:56 +08:00
Taras Yemets
d19aa106f9
feat(cody): add circuit breaker to handle timed-out requests and rate limit hits (#64133)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Closes
https://linear.app/sourcegraph/issue/CODY-2758/[autocomplete-latency]-add-circuit-breaker-in-cody-gateway-to-handle

This PR introduces an in-memory model availability tracker to ensure we
do not send consequent requests to the currently unavailable LLM
providers.

The tracker maintains a history of error records for each model. It
evaluates these records to determine whether the model is available for
new requests. The evaluation follows these steps:
1. For every request to an upstream provider, the tracker records any
errors that occur. Specifically, it logs timeout errors (when a request
exceeds its deadline) and responses with a 429 status code (Too Many
Requests).
2. These error records are stored in a circular buffer for each model.
This buffer holds a fixed number of records, ensuring efficient memory
usage.
3. The tracker calculates the failure ratio by analyzing the stored
records. It checks the percentage of errors within a specified
evaluation window and compares this against the total number of recent
requests.
4. Based on the calculated failure ratio, the tracker decides whether
the model is available:
- Model Unavailable: If the ratio of failures (timeouts or 429 status
codes) exceeds a predefined threshold (X%), the model is marked as
unavailable. In this state, the system does not send new requests to the
upstream provider.
When a model is unavailable, the system immediately returns an error
status code, typically a 503 Service Unavailable, to the client. This
informs the client that the service is temporarily unavailable due to
upstream issues.
- Model Available: If the failure ratio is within acceptable limits, the
system proceeds with sending the request to the upstream provider.

This PR suggests considering a model unavailable if **95% of the last
100 requests within the past minute** either time out or return a 429
status code. I am not sure about these exact values and suggest them as
a starting point for discussion

## Test plan
- Added unit tests
- CI
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-05 11:38:58 +00:00
Keegan Carruthers-Smith
199cab4a1b
gomod: update zoekt for shard scanning improvement (#64264)
This only contains one commit which reduces how often we call scan in
indexserver on dotcom.

- acacc5eda1 shards: only trigger rescan on .zoekt files changing

Test Plan: tested in zoekt CI
2024-08-05 12:36:27 +02:00
Varun Gandhi
a0b2a1dd45
chore: Remove incorrectly logged warning (#64267)
The cursor state can be "" when the data is exhausted.
2024-08-05 09:43:43 +00:00
Varun Gandhi
c8c8f32aff
fix: Handle potential nil reference properly (#64265) 2024-08-05 17:41:09 +08:00
Keegan Carruthers-Smith
e332124698
servicecatalog: remove searcher dep on database (#64247)
Searcher doesn't speak to the database nor has it for a long time. See
https://github.com/sourcegraph/sourcegraph/pull/61463

Test Plan: The following command is empty

  go run ./dev/depgraph/ summary internal/database | grep 'cmd/searcher'
2024-08-05 09:55:49 +02:00
Varun Gandhi
7595615f07
fix: Don't propagate un-translated source ranges (#64263)
The `getSourceRange` function can have a range translation failure,
in which case it would be wrong to propagate the range directly
without the commit information. So skip the ranges in that case.
2024-08-05 15:03:55 +08:00
Varun Gandhi
ef77a1e0e1
fix: Handle sub-repo permissions in CodeGraphData API (#64241) 2024-08-05 12:31:07 +08:00
Jason Hawk Harris
b0702f3c3c
[Svelte]: UI Updates for Perforce Depots and Git Repos (#64014)
Introduces basic (and incomplete) UI support for perforce, including displaying changelist ids,
listing changelists, and removing references to commits and branches.
2024-08-02 20:47:20 -06:00
Vova Kulikov
4caad25380
Cody Web: Update Cody Web to 0.3.6 [React version] (#64254)
Closes
https://linear.app/sourcegraph/issue/SRCH-720/new-chat-button-in-side-panel-view
Closes
https://linear.app/sourcegraph/issue/SRCH-808/chat-history-in-side-panel-view

This PR does a few things 
- Updates Cody Web to 0.3.6 (this includes improvements around mentions
UI, web url mention support, etc)
- Adds "create new chat" button to the sidebar cody chat UI
- Adds history chats UI to the sidebar cody chat UI (note that in GA we
will rely on the new Tabs UI, this history UI is just a temporal
solution for the Sourcegraph Aug release, in sep GA release it will be
improved)

## Test plan
- General manual checks on Cody Web.
- Check that you can create a new chat from the sidebar chat UI
- Check that you can select chats from the history panel from the
sidebar chat UI

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-02 18:04:52 -03:00
Camden Cheek
c643c224ab
Chore: remove non-null assertions (#64249)
Followup from #64236
2024-08-02 15:01:48 -06:00
Camden Cheek
a148d8a670
Web: fix git blame for files that have /stream/ in their path (#64230)
The URL path for streaming blame is ambiguous when the file path
contains `/stream/`. The pattern looks like
`/blame/<repo_name>@<revision>/stream/file/path.txt`. However, if the
file contains `/stream/`, the revision is matched greedily up until the
last stream, so we end up with a revision that looks like
`81af3g/stream/my/path`, which is in invalid revision that results in a
404.

This makes the URL pattern unambiguous by adding a `/-/` element after
the revision, which is not allowed in a revision name and acts as a path
separator. So now, the pattern looks like
`/blame/<repo_name>@<revision>/-/stream/file/path.txt`.

Note, this is a public-facing breaking change, but I don't think it
really matters since I don't expect any customers use our streaming
blame API
2024-08-02 14:11:32 -06:00
Camden Cheek
b4566aae8a
Svelte: fix welcome banner flashing on reload (#64251)
Fixes SRCH-831
2024-08-02 17:16:57 +00:00
sourcegraph-buildkite
8f89c279f7
security: Auto-update package lockfiles for Sourcegraph base images (#64204)
Automatically generated PR to update package lockfiles for Sourcegraph
base images.

Built from Buildkite run
[#285676](https://buildkite.com/sourcegraph/sourcegraph/builds/285676).
## Test Plan
- CI build verifies image functionality

Co-authored-by: Buildkite <buildkite@sourcegraph.com>
2024-08-02 17:54:55 +02:00
Taiyab Raja
e652c7e59e
Styling updates throughout (#64221)
Resurrection of https://github.com/sourcegraph/sourcegraph/pull/64080 --
full details are there
2024-08-02 15:15:06 +00:00
Vincent
1a834fdc4f
fix: block URLs without a hostname (#64248)
In Go it's possible to have URLs without a valid host portion 🤷 .
This has unintended side-effects when filtering hostnames.

## Test plan
Tested that URLs that have no hostname are now blocked.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-02 15:53:33 +01:00
Christoph Hegemann
7fc92a5538
codeintel: make usage-range non-optional (#64236)
Closes
https://linear.app/sourcegraph/issue/GRAPH-727/make-range-for-usagerange-non-optional

## Test plan

Tests continue to pass
2024-08-02 14:51:57 +00:00
Michael Bahr
4a565a8819
fix(batches): show warning instead of error when the changeset status is not FAILED (#64243)
With SRCH-802 we saw error messages when batch changes may still retry
and resolve the problem. To give a better distinction between resolvable
and non-resolvable errors, I'm changing the colour variation from error
to warning if the changeset has not been marked as `FAILED` yet.

Before:

<img width="913" alt="Screenshot 2024-08-02 at 12 44 27"
src="https://github.com/user-attachments/assets/b192c5e9-d23b-460c-82a7-a039edbca3f5">

After:

<img width="1355" alt="Screenshot 2024-08-02 at 12 36 23"
src="https://github.com/user-attachments/assets/02e231a7-168a-4fe9-bd3b-014d810fd236">

## Test plan

Manual testing

## Changelog

- Batch changes that are still retrying now show a warning instead of an
error.
2024-08-02 16:22:30 +02:00
Keegan Carruthers-Smith
f7d62a3076
gitserver: RawDiff checks if commits exist (#64245)
ResolveRevision additionally adds a "^0" to the spec to make sure we
actually check if it exists. This is important, since most uses of the
ChangedFiles API pass in commit shas which do not get resolved by git
unless the "^0" is present.

I noticed this since hybrid search in searcher started to fail if the
commit was missing. In particular Zoekt for empty repositories uses a
fake SHA of 404aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa so when a repo
started getting cloned hybrid search would fail until it was indexed.
Hybrid search explicitly checks for the NotFound error, so hybrid search
failing was a a regression from moving away from the SymbolDiff API.
2024-08-02 13:10:04 +00:00
Erik Seliger
ad4d7177ab
Reapply "soap: Fix auto-redirect to IdP when SOAP is enabled" (#64234) (#64244)
This reverts commit
81585cb7ca.

## Test plan

Tested in dotcom mode locally after clearing cookies and no redirect
happens now.
2024-08-02 12:30:11 +00:00
Stefan Hengl
60c7e9b42f
gomod: update Zoekt (#64238)
ebb3ca2424...764fe4f9de

- https://github.com/sourcegraph/zoekt/commit/c01b6c7778 remove
SRC_EXPERIMENT_ITERATE_NGRAM_LOOKUP_LIMIT
- https://github.com/sourcegraph/zoekt/commit/bbd1fedfcd feat(Search):
Add support for all Apex language extensions
- https://github.com/sourcegraph/zoekt/commit/764fe4f9de index: enable
shard merging by default

Relates to SPLF-175

Test plan:
CI
2024-08-02 13:15:47 +02:00
Varun Gandhi
26c309916e
chore: Use binary search over symbols array (#64240)
Right now, perf is dominated by slowness of gitserver, but let's
avoid the pessimization in the old code with multiple linear lookups.
2024-08-02 10:29:17 +00:00
Petri-Johan Last
44e848d4ba
Enable p4-fusion by default for Perforce code host connections (#64101) 2024-08-02 11:15:16 +02:00
Filip Haftek
e4ebecf205
ephemerals: fix feature flag name (#64237)
Make ephemeral feature flag consistent across sg cli and CloudAPI:
-
[get](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/dev/sg/internal/cloud/instance.go?L193)
is ok
-
[set](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/dev/sg/internal/cloud/instance.go?L206)
was different
- CloudAPI uses now
[this](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/controller/-/blob/cmd/apiserver/api/v1/instance.go?L20)

## Test plan

[e2e against CloudAPI](https://github.com/sourcegraph/cloud/pull/12747)
2024-08-02 10:54:44 +02:00
Varun Gandhi
4f21a5a4b9
chore: De-duplicate CTE for visible uploads (#64232)
The visible uploads detection was copied in yet another place,
so de-duplicate that.
2024-08-02 13:58:33 +08:00
Varun Gandhi
07beaf6bc1
chore: Bump version of sourcegraph/log library (#64233)
I noticed we were using a much older version, so code nav
is a bit janky on S2 as the old version had index data from
lsif-go and not scip-go, causing cross-repo nav from
sg/sg to sg/log to not work.
2024-08-02 13:37:10 +08:00
Varun Gandhi
f9bc3cf1df
fix: Prefer SCIP uploads over LSIF uploads (#64217)
When determining the set of visible uploads at a given commit,
we group uploads from scip-K and lsif-K for ranking purposes
to allow them to shadow each other. Generally, scip-K will end
up shadowing lsif-K, avoiding sending the client a mix of data
from a much older lsif-K index when newer data from a scip-K
index is available.

Fixes https://linear.app/sourcegraph/issue/GRAPH-787

The logic requires some final tie-breaking to avoid non-determinism
in case when there is a scip-K and lsif-K index at the same distance,
which I've done based on the upload_id in descending order
(upload IDs are monotonically increasing). Earlier, some code was
doing tie-breaking based on upload_id in _ascending_ order,
so I've changed that for consistency. This caused some test failures,
so I've updated the corresponding struct literals.

I've left some PR review comments to describe each modification
to the existing test cases.

## Test plan

Added a new dedicated test checking for shadowing behavior.

## Changelog

Fixes a bug where old LSIF uploads would also be used for code
navigation even when newer SCIP uploads were available for the
same language, potentially leading to duplicate results in the reference
panel. With this change, scip-go uploads shadow the uploads
for lsif-go, and similarly for other indexers following the
scip-X/lsif-X naming
convention.
2024-08-02 13:36:50 +08:00
Vova Kulikov
81585cb7ca
Revert "soap: Fix auto-redirect to IdP when SOAP is enabled" (#64234)
Reverts sourcegraph/sourcegraph#64184

The sourcegraph/sourcegraph#64184 is probably caused auth redirect on
dot com. Revert it while we're fixing the original problem

## Test plan

CI
2024-08-02 04:48:21 +00:00
Camden Cheek
ee3a710b7c
Chore: remove enablePreciseOccurrences feature flag (#64229)
Just removes a redundant feature flag.
2024-08-02 00:02:53 +00:00
YK
e6ae7d44b2
fix(docs): update quickstart guide links (#64202)
- Update the "getting started" link in the quickstart guide to point to
the correct URL
- Remove the outdated developer help links as they are no longer
relevant

## Test plan

Test the links manually
2024-08-01 16:18:55 -07:00
YK
83f553e1ec
Update the legacy link to sg doc (#64017)
## Test plan

Check each new link manually

---------

Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com>
2024-08-01 16:18:30 -07:00
Chris Smith
655375de08
Don't block frontend initialization with invalid modelconfig (#64200)
When the `modelconfig` system was introduced, the code was written in a
way to go out of its way to ensure that the configuration data was
correct. Unfortunately, this doesn't interact well with the reality of
the Sourcegraph instance and how site configuration is set.

- Failing to initialize the `modelconfig` component if the site config
is invalid prevents the `frontend` binary from starting up. Leading to
it crash looping / an outage. Not good.
- The site config can be forced-in, regardless of any validators that
are registered. So it's definitely possible for the model configuration
to be invalid.
- Some of our validation checks were a bit too onerous anyways.

This PR refactors the `modelconfig/init.go` file to try really hard to
not fail on application start up. And instead just do its best to
initialize the `modelconfig` service.

- If the site configuration data is invalid, it will just be ignored.
And therefor default to the Sourcegraph instance using Cody Gateway /
Sourcegraph-supplied models.
- If _rendering_ the LLM model configuration fails (e.g. merging the
static configuration and admin-supplied site config), then we just
initialize the modelconfig service with 0 providers, and models. (But
still let things start up.)

These changes should fix
[PRIME-449](https://linear.app/sourcegraph/issue/PRIME-449), but this
still isn't enough for a good user experience. (Since we are now just
swallowing/ignoring modelconfig errors.)

So my next PR will be to add the site configuration validation logic, so
that we surface any of the configuration errors to site admins.

## Test plan

Tested this manually, and could no longer get my `frontend` job to fail
on startup.

## Changelog

NA
2024-08-01 15:56:23 -07:00
Anish Lakhwara
856e41eff3
fix(appliance): Make Appliance URL envvars strings (#64227)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Changes `APPLIANCE_MANAGED` -> `APPLIANCE_UPDATE_TARGET`, and creates
`APPLIANCE_MENU_TARGET`. Both are stringly typed env vars, that when set
will create / redirect the update buttons / menu links in the site admin
and nav item pages.

Paired with @nelsonjr and @DaedalusG on this 

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Manually Tested

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- **fix(appliance): make environment variables strings to be passed
around**
2024-08-01 15:45:25 -07:00
Camden Cheek
aaa464e332
Cody web: add server-side fetching for URL mentions (#64223)
Due to CORS rules, cody web cannot make requests to arbitrary URLs.
Because of this, mentions for URLs do not currently work in Cody Web.

This adds a GraphQL endpoint to the cody context resolvers that resolves
the contents of a mentioned URL.
2024-08-01 16:01:37 -06:00
Camden Cheek
eb1a76ee7a
Svelte: welcome banner followups (#64222) 2024-08-01 15:12:06 -06:00
Vova Kulikov
e073ae59cf
Bump @sourcegraph/cody-web to 0.3.4 (#64224)
Closes
https://linear.app/sourcegraph/issue/SRCH-561/add-support-for-file-ranges-in-cody-web

## Test plan
- Check that you can mention files with ranges
- Check that as you open Cody chat on the blob UI page and you have
selected lines in blob UI then chat should have an initial context
mention with line range
- Check that as you change line selection it updates mention file chip
range (only if you don't have any other text)
2024-08-01 17:30:13 -03:00
Craig Furman
156aa5a0ad
fix(appliance): cache authorization status (#64213)
In order to reduce the cost of calls to auth-gated endpoints, cache
valid admin passwords in-memory. The appliance's frontend calls
auth-gated endpoints in a tight loop, and bcrypt checking is
intentionally an expensive operation.

This could occasionally cause the appliance-frontend to disconnect from
the backend. We observed frontend's nginx reporting an upstream
connection close, and exec'ing into its pod and curling the backend
regularly hung.
2024-08-01 17:38:15 +01:00
Craig Furman
e54407d9f5
fix(appliance): reliably redirect to site-admin post-install (#64216)
When the admin has first installed Code Search Suite, the appliance
waits for the admin to click an "I'm ready" button. This causes the
appliance to unblock a background thread that periodically checks the
health of sg-frontend. When it is healthy, it ensures that the
ingress-facing frontend is pointed to sg-frontend. And when it is not,
it points to the appliance-frontend. Pointing to the appliance-frontend
is its initial state pre-install, and given that we've just installed
sg, the appliance switches the service over quickly.

Meanwhile, clicking this button transitions the frontend to a "refresh"
state (this being one of the states in its state machine). This causes
the UI to reload the web page. The reason we have to do this is that it
is a way to "redirect to yourself". If the ingress-facing service has
been repointed, refreshing like this will show site-admin, which is the
desired behavior. The issue this commit fixes, is that this is racy:
upon refresh, the browser tab queries the appliance (via an nginx proxy
hosted on the same domain serving appliance-frontend) for its state. We
have to store state on the backend (specifically, we use a ConfigMap
annotation), so that the appliance can do the right thing if it has been
rebooted at any time. This will help power future features such as
UI-driven upgrades. The race occurs if, upon refresh, the ingress-facing
service has been flipped over to sg-frontend. The appliance API that
answered the state questions is no longer available!

In general, we can't tell the difference between this expected turn of
events, and a state in which the backend can't be reached. This commit
mitigates the race by setting the appliance UI to refresh if it cannot
reach the appliance API. This looks no different to a "disconnected"
state if things really are broken, but in the expected path, it will
resolve the race by retrying.

This commit reliably causes the appliance-driven installation flow to
redirect to site-admin after clicking "ready", according to my
experimentation in minikube. I suspect that this would be the case even
without https://github.com/sourcegraph/sourcegraph/pull/64213, which
fixes an unrelated performance issue. I suspect we need both, otherwise
the appliance UI will regularly disconnect for prolonged periods of
time, which is confusing.

Closes
https://linear.app/sourcegraph/issue/REL-308/appliance-frontend-seems-to-disconnect-the-backend-during-installation
2024-08-01 17:26:49 +01:00
Julie Tibshirani
5c5ed6ca27
feat(search): remove smart search logic (#64215)
This change removes the backend smart search logic. After this, searches
with smart search enabled (`sm=1`) will be executed in the default
'precise' mode (`sm=0`). For old searches that use `sm=1` and
`patterntype=standard`, it's possible that they will now return no
results.

Looking at telemetry, only 0.1% of searches on dot com trigger any smart
search rule. So this change should only affect a small percentage of
usage. To mitigate the impact on these rare cases, this PR adds an alert
whenever there are no results and smart search is enabled, suggesting
users switch to keyword search. (This will help in the majority of
cases, since the most frequent smart search rule rewrites literal
queries to use 'AND' between terms).

Closes SPLF-92
2024-08-01 18:02:35 +03:00
Vova Kulikov
50dbc74fba
Bump @sourcegraph/cody-web to 0.3.2 (#64195)
This PR brings the most recent version of @sourcegraph/cody-web package
- Improvements in how we fetch providers and debounce logic for their
query
- Fix with switching-chat actions and providers list 

## Test plan
- Manual checks over cody web (React and Svelte version)
2024-08-01 12:01:35 -03:00
Matthew Manela
772e149729
feat(search): Add support to all Apex language extensions (#64194)
Part of
[GRAPH-759](https://linear.app/sourcegraph/issue/GRAPH-759/issue-with-apex-extension-not-appearing-for-langapex)

Linguist only supports a subset of the file extensions often used for
the Apex programming languages. This PR adds support for the main set
commonly used.

**Key changes**
1. Adds all extensions for Apex
2. Update our logic to handle multiple extensions for one language
3. Update tests to ensure we only manually map languages if they don't
exist OR have different extensions in go-enry (prevents us from
duplicating entries completely from go-enry)

## Test plan
- [x] Update unit tests
- [x] Validate locally by testing the language filter
2024-08-01 10:58:59 -04:00
Stefan Hengl
cd38adb4a7
chore(search_jobs): add janitor job (#64186)
Fixes SPLF-119

This adds a background job to Search Jobs that periodically scans for
finished jobs to aggregate the status, upload logs, and clean up the
tables. This drastically reduces the size of the tables and improves the
performance of the Search Jobs GQL API.

For example, with this change, a finished search job on .com only has 1
entry in the database, whereas before it could have several millions if
we searched each repository.

Notes:
- the diff seems larger than it actually is. I left a couple of comments
to help the reviewers.

## Test plan:
- new unit tests
- manual testing:

I ran a couple of search jobs locally (with the janitor job interval set
to 1 min) and checked that
 - logs are uploaded to `blobstore-go/buckets/search-jobs`
 - repo jobs are deleted from `exhaustive_repo_jobs`
 - logs are served from the blobstore after the janitor ran
 - downloading logs while the job is running still works

## Changelog
The new background job drastically reduces the size of the
`exhaustive_*` tables and improves performance of the Search Jobs GQL
API.
2024-08-01 15:29:10 +02:00
Julie Tibshirani
c966d942f7
search: apply phrase boosting to more queries (#64207)
To ease the transition from older search semantics to keyword search, we
[boost matches on
phrases](https://github.com/sourcegraph/sourcegraph/pull/59940). For
example if you search for `// The vararg opts parameter can include`, we
ensure the match in the method comment is highest, even though there
were no explicit quotes in the query.

We decided to limit this boosting to searches with 3 or more terms. With
2 terms, it's possible there are a ton of phrase matches, which can
drown out high quality 'AND' matches. However, we've seen a few dogfood
examples with fewer terms where boosting would have been really useful.

This PR removes the 3 term restriction on boosting. To mitigate noise,
it updates the phrase matching to only match on word boundaries. It also
switches to matching on the original query string instead of
reconstructing the phrase from terms. That lets us match even when
there's special characters, like `return "disabled"`.

Relates to SPLF-168

## Test plan

Adapted unit tests. Lots of manual testing:
* `invalid ModelID`
* `return "disabled"`
* `func TestClient_do(`
* `// The vararg opts parameter can include functions to configure the`
* `test server` -- this still works quite well, it's a bit fragile but
restricting the matches to word boundaries helped reduce noise
* `bytes buffer`
2024-08-01 16:26:41 +03:00
Varun Gandhi
554fd33eff
chore: Factor out sub-query for locating nearest uploads (#64210)
A large sub-query was duplicated between two queries, making
the code harder to understand. This patch factors that out.

Ancillary changes:
- Added more doc comments
- Tweak tests to make failures easier to follow.
2024-08-01 21:05:03 +08:00
Filip Haftek
66be2ddcb6
sg cloud eph: simplify status (#64209)
1. Make `sg cloud eph` instance status Reason simple string, as CloudAPI
will take over and return Reason with job URL - no need to parse Reason
anymore.
```sh
go run ./dev/sg cloud eph status --name ff-eph56
⚠️ Running sg with a dev build, following flags have different default value unless explictly set: skip-auto-update, disable-analytics
 Ephemeral instance "ff-eph56" status retrieved
Ephemeral instance details:
Name                                     Expires In           Instance status                          Details
ff-eph56                                 4h37m4.79031s        unspecified                              creation task is already running: https://console.cloud.google.com/workflows/workflow/us-central1/create-instance-c31bd1a4ea84/executions?project=michael-test-03
```
2. Allow re-run create if CloudAPI returns status with Reason - it means
instance is not fully created yet, so user might re-try create -
CloudAPI will ensure more than one create is not running at the same
time.

3. Updated printers with GOTO action for each instance details:
```sh
go run ./dev/sg cloud eph list --all
⚠️ Running sg with a dev build, following flags have different default value unless explictly set: skip-auto-update, disable-analytics
☁️ Fetched 10 instances
Name                                     Expires In           Instance status                          Details
andre-eph-1                              30h10m42.989163s     unspecified                              invoke: sg cloud eph status --name andre-eph-1
ff-eph56                                 4h34m43.989154s      unspecified                              invoke: sg cloud eph status --name ff-eph56
```

## Test plan

Unit tests simplified.
E2e against old and new CloudAPI.

---------

Co-authored-by: William Bezuidenhout <william.bezuidenhout@sourcegraph.com>
2024-08-01 14:44:03 +02:00
William Bezuidenhout
29847d1ca3
chunk cleaner: remove comment (#64212)
This comment is no longer relevant

## Test plan
CI

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-01 13:48:41 +02:00
Anton Sviridov
7aba4732ee
Policy patch - leave fields unchanged if they're missing from request (#64174)
Fixes GRAPH-782

Specifically this allows us avoid updating syntactic_indexing_enabled
when we don't have the value available.

This is done to solve the problem where not providing that field crashes
the resolver. I confirmed it by both via tests and via manual testing of
the API
![CleanShot 2024-07-31 at 15 51
54](https://github.com/user-attachments/assets/2e82ff20-5541-4a7d-9dd6-17196274d59a)

## Test plan

- Added a new test for resolvers specifically to test the extra logic
around this field
2024-08-01 12:01:26 +01:00
Christoph Hegemann
a64832ab44
refactor: renames usage cursor and adds fields for future syntactic cursor (#64208)
Landing this early to avoid accumulating conflicts

## Test plan

Shouldn't change functionality as new fields are unused for now
2024-08-01 10:36:19 +00:00
Camden Cheek
be17da7305
Svelte: add welcome introduction when enabling svelte for the first time (#64163)
This implements a welcome dialog and some additional messaging around
the beta rollout.
2024-08-01 11:06:37 +02:00
William Bezuidenhout
78064ba956
fix(release): check for marker in container files instead of binary (#64205)
Frontend assets are not embedded into the binary anymore instead they're
added to the final container image at `/assets-dist`.

In this PR we check the directory inside the image for the marker
instead of the binary

Closes DINF-176
## Test plan
Tested locally
```
sg release run test --version 1.2.3
👉 [     setup] Finding release manifest in "."
   [     setup] No explicit branch name was provided, assuming current branch is the target: main
   [     setup] Found manifest for "sourcegraph" (github.com/sourcegraph/sourcegraph)
   [      meta] Owners: @sourcegraph/release
   [      meta] Repository: github.com/sourcegraph/sourcegraph
👉 [      vars] Variables
   [      vars] tag="1.2.3"
   [      vars] config="{\"version\":\"v1.2.3\",\"inputs\":\"\",\"type\":\"patch\"}"
   [      vars] git.branch="main"
   [      vars] is_development="false"
   [      vars] version="v1.2.3"
👉 [      reqs] Checking requirements...
   [      reqs]  jq
   [      reqs] 🔕 Buidkite access token (excluded for test)
   [      reqs] 🔕 GitHub Token to submit changelogs (excluded for test)
👉 [      test] Running testing steps for v1.2.3
👉 [      step] Running step "check:frontend and server image contain bundle"
   [check:frontend and server image contain bundle] pulling frontend image us.gcr.io/sourcegraph-dev/frontend:insiders
   [check:frontend and server image contain bundle] insiders: Pulling from sourcegraph-dev/frontend
   [check:frontend and server image contain bundle] Digest: sha256:1256bfb7c64bee0f11a3d0b82af6899f1d3fe22c0d6f3875a877c5f8f8b0e963
   [check:frontend and server image contain bundle] Status: Image is up to date for us.gcr.io/sourcegraph-dev/frontend:insiders
   [check:frontend and server image contain bundle] us.gcr.io/sourcegraph-dev/frontend:insiders
   [check:frontend and server image contain bundle] checking frontend has web-bundle at /assets-dist inside the container
   [check:frontend and server image contain bundle] WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
   [check:frontend and server image contain bundle] pulling server image us.gcr.io/sourcegraph-dev/server:insiders
   [check:frontend and server image contain bundle] insiders: Pulling from sourcegraph-dev/server
   [check:frontend and server image contain bundle] Digest: sha256:592c4e94ced4990a3b461eb474d5e7fee9c408d93ba4df44220b22f7d39ea645
   [check:frontend and server image contain bundle] Status: Image is up to date for us.gcr.io/sourcegraph-dev/server:insiders
   [check:frontend and server image contain bundle] us.gcr.io/sourcegraph-dev/server:insiders
   [check:frontend and server image contain bundle] checking server has web-bundle at /assets-dist inside the container
   [check:frontend and server image contain bundle] WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
   [      step] Step "check:frontend and server image contain bundle" succeeded
```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog
* release: check contiainer directory `/assets-dist` for marker instead
of frontend binary
<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-08-01 08:25:30 +00:00
Bolaji Olajide
776701ba9c
fix(sg): acknowledge command execution state to avoid recursion when executing short running commands (#64181)
Some commands like the
[`batcheshelper-builder`](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/sg.config.yaml?L821)
aren't long running commands.
This command is used to build and load an image into docker. The `cmd`
section returns an `exit 0`. This behavior combined with
`continueWatchOnExit` results in an infinite loop where the process is
continually restarted because `sg` doesn't know that the process has
finished executing and isn't a long-running process.


https://github.com/user-attachments/assets/e7a027a1-6f93-403f-9240-6a791255fba9

An example of the behavior is shown below as running `sg start batches`
results in the `batcheshelper-builder` command continually restarted.

The fix is quite simple, we return an empty receiver channel when the
process is done executing so that `sg` knows it's done and doesn't
restart the command unless there's a change.

## Test plan

* Manual testing with `go run ./dev/sg start batches` doesn't result in
an infinite loop anymore.
* Add unit tests

## Changelog
2024-07-31 16:09:44 -05:00
Matthew Manela
b2e550c8e5
feat(search): Enable improved symbol parsing for large repos (when using Rockskip) (#63988)
During an investigation, we saw that Rockskip was not using scip-ctags
for symbol parsing when applicable. This means that
1. Rockskip is getting less than optimal symbols for certain languages
(like Go)
2. Rockskip is getting no symbols for languages not in universal ctags
(Magik)

This PR attempts to solve this problem but updating Rockskip to re-use
the ctags parser pool logic from symbol service.

### Key Changes
- Update parser pool to be re-usable
- Push common logic for parser type detection into the parser pool
module
- Update rockskip service config to take a parser pool 
- Update and add unit/integration tests


## Questions
- What performance impact will using this pooled parser have compared to
its previous behavior of spawning a new ctags process each time?



## Test plan
- [x] Add unit tests
- [x] Update integration tests
- [x] Manually test rockskip
- [x] Manually test symbolservice (in case of regression)

---------

Co-authored-by: Keegan Carruthers-Smith <keegan.csmith@gmail.com>
2024-07-31 15:27:31 -04:00
Camden Cheek
60d450b079
Code intel: respect provenance when getting usages (#64193)
This updates the new references panel to respect the provenance of an
occurrence.
2024-07-31 15:50:31 -03:00
Erik Seliger
eb5a0d186c
soap: Fix auto-redirect to IdP when SOAP is enabled (#64184)
When exactly 1 auth provider is configured, Sourcegraph redirects users
automatically to the IdP to speed up the sign-in process, so that users
don't have to make an extra click to select the one and only sign-in
provider.

SOAP is a special case though because it is hidden by default, but
enabled on all cloud instances. That caused this auto redirect to never
fire for Cloud, since there are technically two auth providers.

This PR fixes it by checking for the sourcegraph-operator query
parameter which tells the UI to show the magic SOAP auth provider in the
list.

Closes SRC-500

Test plan: Tested on a cloud instance that indeed there is no auto
redirect. Then tested locally with SOAP configured that auto redirects
happen after this PR, and that there is no auto redirect when the
?sourcegraph-operator query parameter is set.

## Changelog

When only a single auth provider is configured, users are again
redirected correctly to the identity provider on Sourcegraph Cloud.
2024-07-31 20:27:05 +02:00
Anish Lakhwara
c1ff60f082
feat(appliance): Change site-admin updates button to point to Appliance based on env var (#64167)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
This PR resolves
[REL-300](https://linear.app/sourcegraph/issue/REL-300/put-update-redirect-into-current-sourcegraph-admin-panel).
We point the Update button in the SiteAdmin sidebar to point to a
different URL (Currently appliance localhost port, needs to be changed)
based on the `APPLIANCE_MANAGED` env var.

Most of the PR is tracking types / config down to the backend. There, a
simple function checks for the existence of this env var and if it
exists returns it's value.

I may have updated extra unnecessary types (not certain) but I was
following the compiler.

Second commit is just updating the storybook type values

We'll need another PR to the Helm chart to activate the env var once we
want to switch people over to pointing to the appliance maintenance UI.

@DaedalusG brought up the good point that even when managed by
Appliance, the Upgrades page still provides valuable information to
administrators, and so we may or may not actually want to leave this the
way it is.

TODO:
- [ ] Change the URL that is pointed to when the env var is active
(listed in a comment)
## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Tested manually

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- **feat(appliance): change update endpoint based on env var**
- **misc: add type to storybook**

---------

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-31 16:51:56 +00:00
Warren Gifford
a2f39bf302
feat(appliance): introduce mock up database configuration step in install flow (#64162)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Initial demo version of the database config on installation of a new
Sourcegraph search instance managed by Appliance

Currently the disabled external db form and tab options are mock ups
that don't do anything.

<img width="620" alt="Screenshot 2024-07-31 at 3 06 56 AM"
src="https://github.com/user-attachments/assets/98f87ba5-3825-432e-90c9-18c0513325a7">
<img width="830" alt="Screenshot 2024-07-31 at 3 07 09 AM"
src="https://github.com/user-attachments/assets/ad820705-4910-4949-b9cc-d5070024d31c">
<img width="837" alt="Screenshot 2024-07-31 at 3 07 18 AM"
src="https://github.com/user-attachments/assets/c4839fe4-a70f-4b65-a40f-c5ba1fed85d6">


## Test plan
Tested locally

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-31 16:05:20 +00:00
Craig Furman
45630b23ac
feat(appliance): version selector defaults when relreg down (#64173)
Basic fallback. See comments for a potential replacement. Even so, this
gets us moving on day 0.

Closes
https://linear.app/sourcegraph/issue/REL-313/handle-for-releaseregistry-down-in-install-page.
2024-07-31 16:28:31 +01:00
Peter Guy
f8cc07220a
chore/executors: Native Kubernetes Executors default to use single job pod (#64088)
For Executors on Native Kubernetes deployments, the option to run jobs
in a single pod has been available since Native Kubernetes has been
around.

The purpose of running jobs in a single pod is:
1. Efficiency. Jobs require three steps at least, and without specifying
a single pod, that requires spinning up three pods.
2. Security. For Batch Changes, when jobs are run across several pods,
`git`'s `safe.directory` must be set to avoid untrusted users or
processes injecting code or an attack. Running the job in one pod
removes the need for `safe.directory`.
3. Usability. Because of the need to set `safe.directory`, `root` access
to write to `git`'s global config is required, which means that many
times special configurations and sign-offs from security teams must be
used for Batch Change setups.

This PR takes a step toward using single pod jobs only in enabling them
by default instead of requiring an environment variable to enable them.

The same environment variable that was used to enable them -
`KUBERNETES_SINGLE_JOB_POD` - is still available to disable them by
setting it to `false`.

## Test plan

Bazel and CI for now

## Changelog
2024-07-31 08:07:06 -07:00
William Bezuidenhout
8a3e4c3bcc
fix(sg): cloud ephemeral - do no trigger builds on main-dry-run (#64190)
Triggering cloud ephemeral builds on main-dry-run leads to unexpected
results which is due to how the eventual pipeline is generated.

Closes DINF-165

### Generated pipeline?
The pipeline gets generated based on _what matches first_. We detect
cloud ephemeral builds if there is an environment variable
`CLOUD_EPHEMERAL=true`. We detect main-dry-runs if the branch prefix is
`main-dry-run`...

Now due to the `main-dry-run` match happening before the cloud ephemeral
match a Cloud Ephemeral build on a main dry run gets detected as _just_
a `main-dry-run` build.

#### Alternatives
Sure we can just move the Cloud Ephemeral match earlier, but it's
difficult to say what else might break. We could also just add the we
force the runtype to always be `CloudEphemeral` if we're on the Cloud
Ephemeral pipeline, but I don't want to make the pipline a special
snowflake and detect the current pipeline just for Cloud Ephemeral.

#### Why deny it the deployment?
Ultimately, `main-dry-run` builds are meant for ... `main` not cloud
ephemeral. People can just switch to their original branch and run `sg
cloud eph deploy` and the branch will be deployed with no issue

## Test plan
Executed locally
```
./sg-test cloud eph build
⚠️ Running sg with a dev build, following flags have different default value unless explictly set: skip-auto-update, disable-analytics
⚠️ Triggering Cloud Ephemeral builds from "main-dry-run" branches are not supported. Try renaming the branch to not have the "main-dry-run" prefix as it complicates the eventual pipeline that gets generated

  To rename a branch and launch a cloud ephemeral deployment do:

  1.  git branch -m "main-dry-run/lol" <my-new-name>
  2.  git push --set-upstream origin <my-new-name>
  3. trigger the build by running  sg cloud ephemeral build
  FAQ https://www.notion.so/sourcegraph/How-to-deploy-my-branch-on-an-ephemeral-Cloud-instance-dac45846ca2a4e018c802aba37cf6465?pvs=4#20cb92ae27464891a9d03650b4d67cee


 failed to trigger epehemeral build for branch: main-dry-run branch is not supported
```

## Changelog
* sg: deny deployment of `main-dry-run` branches on Cloud Ephemeral.
2024-07-31 16:16:29 +02:00
William Bezuidenhout
972ee32351
feat(frontend): do not embed frontend assets anymore (#63946)
* Frontend no longer embeds the assets intead it reads from the local
filesystem assets.
* Generally the frontend and server cmd targets will use the
`//client/web/dist:copy_bundle` target to create a tarball for the
oci_image. `copy_bundle` puts all the assets at `assets-dist`
* For integration tests, frontend and server have the `no_client_bundle`
target variants. For these oci_images, instead of the `tar_bundle` which
is just a tar'd `copy_bundle` we use the `tar_dummy_manifest` which is
just a tar that contains a dummy manifest.
* By default we expect assets to be at `/assets-dist`
* Renamed DevProvider to DirProvider

## Why
By 'breaking' the dependency of frontend requiring assets to be built we
essentially stop a common cache invalidation scenario that happens:
- someone makes a frontend change = assets need to be rebuilt

By decoupling assets from the frontend binary and moving the packing of
assets to the building of the frontend and server images we will have a
better cache hit rate (theoretically).

Thus with this change, when:
* client/web is change and nothing else ... only assets will have to
rebuilt and cached versions of the backend will be used
* if only backend code has changed ... cached assets will be used

Closes DINF-115

## Test plan
  sg start - web app opens and can search. Local dev assets get loaded
 sg test bazel-integration-test - server image gets built with **only**
dummy web manifest. Also verified by running `sg bazel run
//cmd/server:no_client_bundle.image` and then inspect container
 sg test bazel-e2e - server image gets built with bundle and all tests
pass
 [main dry
run](https://buildkite.com/sourcegraph/sourcegraph/builds/284042#0190e54c-14d9-419e-95ca-1198dc682048)

## Changelog
- frontend: assets are no longer bundled with binary through `go:embed`.
Instead assets are now added to the frontend container at `assets-dist`.
2024-07-31 15:17:52 +02:00
Noah S-C
1538e42180
chore(bazel): emit json profile for image push jobs (properly) (#64189)
Typo when copying the flags from somewhere else, names mismatched and
didnt upload 🤦

Also adding in proper BEP emitting, it appears the build_event_log.bin
that was being output was actually for the honeyvent bazel invocation

## Test plan

CI main dry-run
https://buildkite.com/sourcegraph/sourcegraph/builds/285375

## Changelog
2024-07-31 13:46:15 +01:00
Christoph Hegemann
4757122577
docs: Weaken guarantees for Usage cursor (#64185)
Really we just want to communicate that we might return a few more
results than requested

## Test plan
Just a doc change
2024-07-31 20:16:28 +08:00
Noah S-C
6d3e4a5b74
chore(bazel): emit json profile for image push jobs (#64188)
For more insights into whats happening during those damn build commands

Also removes emitting to honeycomb, that was my experiment that has
concluded.

## Test plan

CI

## Changelog
2024-07-31 12:11:54 +00:00
Jean-Hadrien Chabran
7e7e7c08a1
Revert "chore(ci): post instructions for PR sections in a comment" (#64187)
Reverts sourcegraph/sourcegraph#64176

Test-plan: CI
2024-07-31 13:10:06 +01:00
Varun Gandhi
5409f631e9
chore: Rename type Bytes -> Size (#64183)
The old name 'Bytes' made it sound like it was supposed
to hold a []byte or a similar structure, whereas the type
actually represents a _size_ (in units of bytes).
2024-07-31 11:37:12 +00:00
sourcegraph-buildkite
39a34f7a1a
security: Auto-update package lockfiles for Sourcegraph base images (#64060)
Automatically generated PR to update package lockfiles for Sourcegraph
base images.

Built from Buildkite run
[#285266](https://buildkite.com/sourcegraph/sourcegraph/builds/285266).
## Test Plan
- CI build verifies image functionality

Co-authored-by: Buildkite <buildkite@sourcegraph.com>
2024-07-31 11:31:19 +01:00
Christoph Hegemann
5affc2dba5
chore(codeintel): replaces lsp.Range uses with scip.Range (#64178)
Collecting some red-line brownie points

## Test plan
Existing tests continue to pass
2024-07-31 12:25:33 +02:00
Varun Gandhi
53871e771a
chore: Replace calls to deprecated ioutil.TempFile -> os.CreateTemp (#64177) 2024-07-31 11:59:41 +02:00
Varun Gandhi
ab2697a0d6
fix: De-dup and concurrent-ify file content requests & splitting (#64169)
This speeds up precise find usages from about 600ms to 400ms
for a test workload involving 16 precise usages across 5 files.

(Specifically for the `codenav.Service` type)

Fixes GRAPH-781

I have some more thoughts on speeding this up further, but
I'll likely look into that after adding tests.
2024-07-31 17:46:33 +08:00
Jean-Hadrien Chabran
76210386a6
chore(ci): post instructions for PR sections in a comment (#64176)
Follow-up to https://github.com/sourcegraph/devx-support/issues/1130 

Moving the doc links to a comment is merely a few lines of GitHub
Script, so it's worth doing it for better merge commit messages.

## Test plan

This PR itself was the test, as you can see below the comments that
resulted from this new GH workflow. Btw, the second one is the one
you'll see in the code here. I went for a oneliner to avoid cluttering
the UI.
2024-07-31 09:37:39 +00:00
Jean-Hadrien Chabran
8ef716d350
chore(local): remove docsite from most commandsets (#64175)
We don't need the docsite to run on most command sets, this PR simply
removes it for those.

## Test plan

CI
2024-07-31 09:33:23 +00:00
Rafał Gajdulewicz
47e9cdff3e
Expose ranker relevance score in GraphQL API (#64172)
This PR exposes per-item relevance score (as assigned by the re-ranker)
in the GraphQL `rankContext` endpoint. Before, we only ordered the
items, but didn't return relevance information.

## Test plan

- tested locally
2024-07-31 09:12:52 +00:00
Julie Tibshirani
f4a07a8b12
fix(search): correctly handle select:symbol.enum (#64170)
To implement `select:symbol.enum` filters, we look at each symbol's
ctags 'kind' and check if it matches the filter value `enum`. We
accidentally didn't include 'enum' in this match logic, so all these
symbols were filtered away.

This PR fixes that, and adds a few improvements:
* Use a shared map between `symbol.LSPKind` and `symbol.SelectKind`, to
avoid drift between these two conversions.
* Audit the ctags mapping from
[sourcegraph/zoekt#674](https://github.com/sourcegraph/zoekt/pull/674)
and add other missing kinds (besides enum)

Closes SPLF-178
2024-07-31 12:07:27 +03:00
Varun Gandhi
d17660dafd
docs: Specify matching behavior for usagesForSymbol(range:) (#64151)
Noticed a TODO in the GraphQL schema docs, so figured I'd fill that out.
2024-07-31 14:53:45 +08:00
Varun Gandhi
43b4341a25
chore: Unconditionally call endObservation (#64150)
I think the span will not be terminated if we don't call `endObservation`.
Not the end of the world since this span likely won't be useful,
but we should avoid skipping calls to `endObservation` for consistency.
2024-07-31 06:15:18 +00:00
Varun Gandhi
8f2479edd2
feat: Add support for precise usagesForSymbol (#64126)
This patch wires up the newly changed APIs in #64118 
to the GraphQL API, enabling precise support in the
usagesForSymbol API. It also handles pagination.

Fixes https://linear.app/sourcegraph/issue/GRAPH-573

## Test plan

Manually tested. Will add automated tests in follow-up PR.

## Changelog

- Adds support for precise code navigation to the experimental
`usagesForSymbol` API, which can be used to implement a
  reference panel or similar functionality.
2024-07-31 13:55:07 +08:00
Stephen Gutekanst
01bb57c4c3
fix autocomplete regression in main ("various" provider issue) (#64165)
This fixes the current regression of autocomplete in `main`, which
occurs both when (and sometimes when not) using the new
`modelConfiguration` site config option.

In 3cb1c4528d (which lives only in `main`,
not in any official releases - except those images that went to
Self-hosted models EAP customers.) we had a regression where
`CodyLLMConfiguration.provider` would return `"various"`.

This change makes it so that we never return `"various"`, and instead
only return provider values that would be accepted by the autocomplete
provider tests of the client (`create-provider.test.ts`)

This change was based purely on evaluating what the client actually does
with this data, see the code comment (a story / explanation in itself)
for details.

## Test plan

* I am 100% confident the current "various" behavior is absolutely
incorrect, and currently has broken autocomplete in `main` - so this
change (even if it turns out to be slightly incorrect and needs a small bit more work) is a major
improvement over the current state of `main`.
* After merge, I'd like to confirm with a good amount of manual testing
that the various autocomplete providers work as expected.

Note: there is no changelog entry because this regression did not ship yet. It was in `main` prior to this commit, but not in any official releases of Sourcegraph.

## Changelog

N/A

---------

Signed-off-by: Stephen Gutekanst <stephen@sourcegraph.com>
Co-authored-by: Chris Smith <chrsmith@users.noreply.github.com>
2024-07-31 04:13:47 +00:00
Stephen Gutekanst
544d261e66
replace modelOverridesRecommendedSettings with selfHostedModels (#64164)
Previously, for providing self-hosted model' configuration (the models
we've tested and believe work well), a site admin would use
configuration like this:

```
"modelConfiguration": {
    ...
    "modelOverridesRecommendedSettings": [
      "mistral::v1::mixtral-8x7b-instruct",
      "bigcode::v1::starcoder2-7b"
    ],
}
```

A few problems with this:

1. If you are NOT self-hosting models, you probably really should not be
using this option, as it would set `serverSideConfig` options specific
to self-hosting, but it's naming "recommended settings" which kind of
suggests otherwise!
2. When self-hosting models, there is almost a 1:1 correlation of
`provider` to actual API endpoint (because you have a single endpoint
per model) - so not being able to configure the `mistral` or `bigcode`
parts of the modelref above is problematic (restricts you to hosting
'only one model per provider'). The only escape for this currently is to
abandon the defaults we provide with `modelOverridesRecommendedSettings`
and rewrite it using `modelOverrides` fully yourself.
3. When self-hosting models, needing to configure the
`serverSideConfig.openaicompatible.apiModel` is a really common need -
the most common option probably - but again there's no way to configure
it here, only option is to abandon defaults and rewrite it yourself.
4. If we improve the default values - such as if we learn that a higher
context window size for `mixtral-8x7b-instruct` is better - we currently
don't have a good way to 'release a new version of the defaults' because
the string is a model ref `mistral::v1::mixtral-8x7b-instruct` we'd have
to do this by appending `-v2` to the model name or something. Having
versioning here is important because there are both:
* Breaking changes: if we increase the context window at all, site
admins hosting these models may need to increase limits in their hosted
model deployment - or else the API may just return a hard error ('you
sent me too many tokens')
* Non-breaking changes: if we _decrease_ the context window, Cody
responses will get faster, and it's fine to do. Similarly, adding new
stop sequences may be fine for example.

This PR fixes all of these^ issues by deprecating
`modelOverridesRecommendedSettings` and introducing a new
`selfHostedModels` field which looks like:

```
"modelConfiguration": {
    ...
    "selfHostedModels": [
      {
        "provider": "mistral",
        "model": "mixtral-8x7b-instruct@v1",
        "override": {
          "serverSideConfig": {
            "type": "openaicompatible",
            "apiModel": "mixtral-8x7b-instruct-custom!"
          }
        }
      },
      {
        "provider": "bigcode",
        "model": "starcoder2-7b@v1",
        "override": {
          "serverSideConfig": {
            "type": "openaicompatible",
            "apiModel": "starcoder2-7b-custom!"
          }
        }
      }
    ],
}
```

Notably:

* The `provider` part of the model ref is now configurable, enabling
self-hosting more than one model per provider while still benefitting
from our default model configurations.
* `"model": "starcoder2-7b@v1",` is no longer a model ref, but rather a
'default model configuration name' - and has a version associated with
it.
* `override` allows overriding properties of the default `"model":
"starcoder2-7b@v1",` configuration, like the
`serverSideConfig.apiModel`.

## Importance

I'm hoping to ship this to a few customers asap;

* Unblocks customer https://linear.app/sourcegraph/issue/PRIME-447
* Fixes https://linear.app/sourcegraph/issue/PRIME-454 (you can see some
alternatives I considered here before settling on this approach.)

## Test plan

Manually tested for now. Regression tests will come in the near future
and are being tracked on Linear.

## Changelog

Improved configuration functionality for Cody Enterprise with
Self-hosted models.

---------

Signed-off-by: Stephen Gutekanst <stephen@sourcegraph.com>
2024-07-30 20:41:23 -07:00
Erik Seliger
1736876d87
chore: move internal/suspiciousnames to cmd/frontend/internal (#64071)
Just another package that is now only used by frontend, so moving it
around to make clearer which service needs this package.

Test plan: Go compiler doesn't complain about moved directory.
2024-07-31 04:42:08 +02:00
Erik Seliger
eee2053b47
chore: remove cmd/frontend/external redirection package (#64070)
This package is no longer required now that everything that depends on
session is inside cmd/frontend. This removes one layer of indirection in
the code nav flow.

Test plan: Just removed aliases and pointed to the original code, and
the Go compiler doesn't complain.
2024-07-31 04:41:59 +02:00
Erik Seliger
e6d4801b20
chore: move cmd/frontend/oneclickexport to cmd/frontend/internal/oneclickexport (#64069)
This package is only used inside frontend, so no need to expose it
publicly.

Test plan: Just moved one folder, Go compiler doesn't complain.
2024-07-31 04:41:49 +02:00
Erik Seliger
515acb8b27
chore: Simplify license routines (#64068)
There's no need to track they haven't been called twice, this is a
programming error and should not happen. We don't need to maintain a
global int for that, IMO which just makes it harder to call in tests
etc.

Test plan: Local stack still works, code review.
2024-07-31 04:34:39 +02:00
Erik Seliger
c44ffb0d74
chore: Remove unused loghandlers package (#64067)
This package is not imported anywhere anymore, so we can safely drop it.

Test plan: Go compiler doesn't complain after package was removed.
2024-07-31 04:34:22 +02:00
Erik Seliger
32e58ad055
chore: Deglobalize oneclickexporter instance (#64066)
This PR removes the requirement that a global variable is initialized in
the frontend main function. Instead, we create a data exporter where
it's used.

Test plan: CI passes, code review.
2024-07-31 04:34:12 +02:00
Erik Seliger
3413c37c64
chore: move internal/highlight to cmd/frontend (#64065)
Only frontend uses this package, so moving this package here to make
clearer what service depends on this code.
This package also requires a call to the Init() func which only frontend
does right now, so this also was a footgun where someone might start
using this package outside of frontend, but then it's not correctly
initialized.

Test plan: Just moved a package, go compiler doesn't complain.
2024-07-31 04:34:03 +02:00
Erik Seliger
23ebac34d1
chore: move internal/conf/validation to cmd/frontend (#64064)
Only frontend uses this package, so moving this package here to make
clearer what service depends on this code.

Test plan: Just moved a package, go compiler doesn't complain.
2024-07-31 04:23:37 +02:00
Erik Seliger
a156ee6afe
auth: Fix Found page response when redis is down (#64063)
At some point, we decided to serve a 500 error instead of a 302 FOUND
which redirects to the sign in page when redis is down. This usually
happens during a rollout because redis is usually also rolled out at the
same time.
When that happens, users would previously get redirected to the signin
page, and their session is cleared.

So we decided to instead send a 500 status code, and let them explicitly
retry.

However, that didn't stop the execution chain before, so we would send
the 500 status code, but then eventually get to the app handler that
calls http.Redirect with 302 FOUND (which as a side-effect renders a
`Found.` link as an HTML page for old browsers that don't support 302
natively). Since the http status header has already been sent, it
doesn't change the status code to 302 and instead returns a 500 response
with the HTML `Found.` link.

This is the strange error page we've been seeing during rollouts a lot
of times and never knew where it's from.

Test plan: Locally stopped redis while the instance was running and no
longer saw the `Found.` message and instead now get a proper error
message.
2024-07-31 04:15:29 +02:00
Erik Seliger
7a7c663816
chore: Remove redis init side-effect of app.NewHandler (#64062)
This current code sets a global variable which couples the session
package and the app package and the session package cannot work when the
NewHandler method wasn't called yet.

This also used to wait for redis implicitly, without any indication of
doing that.

To be more explicit about that, we now do that in the main function of
frontend instead, and create the session store where required on the
fly.

Test plan: Login still works, integration/E2E tests are passing.
2024-07-31 04:15:17 +02:00
Erik Seliger
03c2907a82
chore: Init userpasswd provider where we initialize every other authn provider (#64061)
Just a little cleanup which makes the main function a bit shorter and
easier to understand that userpasswd is not different to other authn
providers.

Test plan: Authn with builtin still works in CI integration tests.
2024-07-31 04:09:25 +02:00
Erik Seliger
35dcea121f
chore: Remove global externalURL watcher (#64058)
This removes the need to register a global URL watcher. Instead, the
conf package now returns a cached version, and also makes a copy of it
so it's impossible to accidentally modify it.

This makes it safe in non-cmd/frontend packages to use this.

Test plan: All tests are still passing.
2024-07-31 03:43:28 +02:00
Erik Seliger
56467e3c48
cleanup: Move azure openai provider config validation to right place (#64056)
This validation was done in the azure oauth provider, which mixes two
separate domains.

Test plan: CI, code review.
2024-07-31 03:43:17 +02:00
Erik Seliger
4bbb45ad3b
chore: Don't pass nil context (#64055)
This doesn't blow up, but golangci-lint complains about it so following
best practices here.

Test plan: Go test still passes, linter doesn't complain anymore.
2024-07-31 03:43:06 +02:00
Erik Seliger
f09d8d277d
chore: Remove cmd/frontend/external/app (#64054)
Since we don't do the enterprise/oss split anymore, this global package
is no longer required and we can move the code to where it's actually
used.

Test plan: Go compiler doesn't complain, and integration tests are still
passing.
2024-07-31 03:42:55 +02:00
Erik Seliger
4cbbcdb3a2
licensecheck: Make proper goroutine (#63655)
This code was using a strange pattern that isn't actually observed or
controlled by our worker mechanisms, so switching it to return proper
goroutines.

Test plan: CI passes, would like a thorough review on the licensecheck
code.
2024-07-31 03:42:38 +02:00
Erik Seliger
b89ed0fea7
chore: Make return type more obvious (#63651)
These functions return StoreOpts, but that wasn't immediately clear, so
adding this small tweak here.

Test plan: Ci passes.
2024-07-31 03:42:18 +02:00
Erik Seliger
a0c7683570
subrepo: More explicitly define supported hosts (#63650)
This takes less hoops to find what we support, and we don't extend this
any time soon.

Test plan: CI passes.
2024-07-31 03:41:50 +02:00
Erik Seliger
64995a17bc
Move internal/session into cmd/frontend/internal (#63649)
Only frontend handles user sessions, so moving it into this package to indicate that properly.

Test plan: Go compiler doesn't complain.
2024-07-31 03:33:53 +02:00
Erik Seliger
c4c375a642
chore: Move authn into cmd/frontend (#63648)
They should not be used outside of cmd/frontend, so making it a frontend
internal package.

While doing that, I realized that there is a coupling dependency between
authz providers and auth (which is authN) providers: GitLab code host
connections can do authz mapping via the usernames of another OIDC or
SAML auth provider
(https://sourcegraph.com/docs/admin/code_hosts/gitlab#administrator-sudo-level-access-token).
It turns out this feature does not work anymore, since at least several
releases, because we don't actually instantiate auth providers outside
of `cmd/frontend` and thus the mapping will never find anything (auth
providers don't explode when queried before init, unlike authz).
This only now became clear as I moved this code, and the dependency
graph was broken, so that's a nice property of these cleanups I guess 😬
Since it doesn't seem to work for quite some time, I opted for removing
it, and added a changelog entry about it. Not sure if that is
sufficient, I raised a thread here:
https://sourcegraph.slack.com/archives/C03K05FCRFH/p1721848436473209.
This would've prevented this change and needed more refactoring as
unfortunately we cannot map an auth provider by the conf type to a
record in the `user_external_accounts` table and need to actually
instantiate it.

Test plan: Compiler doesn't complain, tests still pass.

## Changelog

GitLab code host connections were [able to sync permissions by mapping
Sourcegraph users to GitLab users via the username property of an
external OIDC or SAML
provider](https://sourcegraph.com/docs/admin/code_hosts/gitlab#administrator-sudo-level-access-token)
that is shared across Sourcegraph and GitLab. This integration stopped
working a long time ago, and it has been removed in this release.
2024-07-31 03:26:25 +02:00
Erik Seliger
38b79fbb2f
authz: Compute providers on the fly (#64012)
Previously, we would store authz providers globally and refresh them
every now and then.
However, creating the providers is fairly cheap (1.3ms in a local trace)
so we should not keep them in memory and remember to not forget to start
the watcher routine.

This will help for multi-tenant Sourcegraph in that providers are now
computed for the context in question, and not held globally. Keeping
potentially 100k authz providers in memory will not scale.

Test plan: Still works, local Jaeger traces are quite acceptable.
2024-07-31 02:59:41 +02:00
Erik Seliger
c917330d6b
authz: Drop requirement for installing authz providers in every service (#63743)
This is a register call that is easy to forget. When forgotten, all queries against the repo store will block forever.

In addition, this adds a hard-dependency on conf to every services startup, plus a busy loop. With multi-tenant, this will not work great because authz providers would be a global, and we instead want most things to be ephemeral so they're per-provider. This is a step toward that, but doesn't yet remove the providers global variable.

Good news, it turns out that we don't actually need to register the providers in every service! The reason they were required was to check if zero providers are configured, or if authzbypass mode is enabled.

Authz bypass mode is usually ON, except when there are problems with the authz providers, meaning some authz providers might not be able to sync permissions. Bypassing of permissions is only ever happening if there are ALSO zero providers configured.

So this is basically an optimization for the case where an instance has zero authz configured so that the SQL queries are a bit simpler. This also helps in tests because with bypass mode on and no providers configured, authz enforcement is effectively off in the repo store.
This makes it so that in tests we need to do slightly more work, but also makes for a more realistic test vs at runtime setup. Also, it's highly recommended to use mocks for DB wherever possible in more high-level components to keep tests fast.

To never have a scenario where we accidentally mess up here and enable bypass mode erroneously, this PR drops that entirely. Authz is always enforced, but when a code host connection is unrestricted (i.e., will not spawn a provider) the repos are still visible, so this should be no change over before.

## Test plan

The stack starts and works, and all CI tests are still passing. Code review should help as well.
2024-07-31 01:23:34 +02:00
Chris Smith
32720268cc
Relax modelconfig name restrictions (#64161)
This PR greatly relaxes the naming restrictions for resource IDs when
using the new `modelconfig` LLM model configuration system.

The original intent was to set a high bar for how we would allow users
to refer to LLM providers, API versions, or models. So that we could
have use those names in URLs and/or display them if no human-friendly
name was supplied. e.g. `opanai::v1::gpt-3.5-turbo`.

However, in practice, this was just a bit too optimistic. We already had
carved out an exception for "API versions" to be less strict, since
there were some cases where we saw those included slashes and things.
And one of our trusted testers immediately ran into problems because the
model name had an `@` in it. (See the linked issue.)

In order to avoid perpetually trying to work around LLM providers and
whatever IDs they use for things, it seemed preferable to just relax our
rules.

With this PR, we will constraint Provider, API Versions, and Model IDs
to only be URL-safe(*). So previously characters like `[]@/+;!` were
prohibited, they are now allowed.) However, we still restrict names to
only include `a-zA-Z` and no unicode characters, and curly braces are
not allowed. (But `[]` and `()` are.

> Pedantically, we do not want to say they are _exactly_ URL safe.
Because we don't perform any sort of escaping (e.g. "%20" -> " ", etc.)
Nor do we allow the `:` which _is_ allowed by the RFC, since we are
using that to delimit parts of the model ref.

Anyways, this should provide enough flexibility to avoid most (hopefully
all) problems users would encounter. While still enforcing some type of
standards with regard to how models are defined.

Fixes [PRIME-451 : invalid ModelID (claude-3-5-sonnet@20240620) after
upgrading to
5.5.2463](https://linear.app/sourcegraph/issue/PRIME-451/invalid-modelid-claude-3-5-sonnet20240620-after-upgrading-to-552463).)

## Test plan

Added tests.

## Changelog

NA.
2024-07-30 15:20:22 -07:00
Noah S-C
adef82f9ed
feat(bazel): read binary version info from accompanying files in OCI images instead of stamping //internal/version (#63977)
https://linear.app/sourcegraph/issue/DINF-111/rework-how-we-inject-version-in-our-artifacts

Pros:
- saves having to rebuild `bazel query 'kind("go_library", rdeps(//...,
//internal/version))' | wc -l` == 523 Go packages when stamp variables
cause a rebuild
- Cutting out GoLink action time when stamp changes but code is cached

Cons:
- Binaries themselves are no longer stamped, only knowing their version
info within the context of the docker image
- A tad extra complexity in internal/version/version.go to handle this
new divergence

---

Before:
```
$ bazel aquery --output=summary --include_commandline=false --include_artifacts=false --include_aspects=false --stamp 'inputs(".*volatile-status\.txt", //...)'

  Action: 1
  Genrule: 2
  Rustc: 3
  ConvertStatusToJson: 88
  GoLink: 383
```

After:
```
$ bazel aquery --output=summary --include_commandline=false --include_artifacts=false --include_aspects=false --stamp 'inputs(".*volatile-status\.txt", //...)'

Mnemonics:
  Genrule: 2
  Action: 3
  Rustc: 3
  ConvertStatusToJson: 86
```

## Test plan

Lots of building & rebuilding with stamp flags, comparing execution logs
& times

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 20:52:01 +00:00
Chris Smith
3b3749f559
Add unit test for modelconfig converting starcoder completion model (#64160)
There was some confusion about how a starcoder model would "come out" of
the modelconfig system. Added a unit test and some clarifying comments
to hopefully help out.

## Test plan

Just add tests for the sake of clarifying the code.

## Changelog

NA
2024-07-30 13:00:26 -07:00
Warren Gifford
84e28998e9
bug(appliance): fix default version (#64143)
Currently the default selected version may not be in the set of filtered
versions available in the selection dropdown resulting in an empty
default. Fix with sequencing of `setSelectedVersion`

Also changed a variable name

## Test plan
tested locally

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 10:07:52 -07:00
Michael Lin
4a04287e53
ci: add cloud controller gql compat test (#64092)
closes CLO-527


[context](https://sourcegraph.slack.com/archives/CHXHX7XAS/p1721835847010889)

cloud uses a lot of the GraphQL API to pre-configure instances on
customer behave, and it's very sensitive to breaking changes to the
schema upstream.

currently, we have a [cronjob github
actions](https://github.com/sourcegraph/controller/actions/workflows/srcgql-compat.yaml)
that periodically check the schema compatibility every day.

such approach works but we're always playing catch up and will have to
result in extra work on the product team to re-work the PR. it is much
better to catch this in CI time within the monorepo.

This PR added a new github actions to the monorepo that will run on any
`*.graphql` changes. Then it will remotely trigger the cronjob github
action in sourcegraph/controller to run and poll the result. See test
plan for demo.

## FAQ

### Why not run the test in buildkite or directly in this repo using
github actions?

- sourcegraph/controller is a huge repo forhistorical reason (> 2G) and
cloning it is very expensive
- the repo contains sensitive information, and we don't want to make it
possible to expose it accidentally.

### How does authentication work?

We use a [GitHub
App](https://github.com/organizations/sourcegraph/settings/apps/cloud-srcgql-compat-test-invoker)
with extremely limited permissions. It only permits the workflow to
trigger/read the workflow without any access to the source code itself.

Also, GitHub App installation access token has a life span of 1h, much
better than PAT.

![CleanShot 2024-07-25 at 21 58
44](https://github.com/user-attachments/assets/ef29a95d-5465-4e19-ab81-1dd22d14ebd7)

## Test plan

it triggered the job and it worked:

good: https://github.com/sourcegraph/sourcegraph/pull/64094
bad: https://github.com/sourcegraph/sourcegraph/pull/64095
2024-07-30 10:06:49 -07:00
Jason Hawk Harris
6f5de6ded7
Nit: adds space between tools menu item and dropdown icon (#64154)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Before: 
<img width="98" alt="Screenshot 2024-07-30 at 11 24 29 AM"
src="https://github.com/user-attachments/assets/b62700ab-6cf9-499c-a2dd-8241587abd35">

After: 
<img width="104" alt="Screenshot 2024-07-30 at 11 24 09 AM"
src="https://github.com/user-attachments/assets/16bc4153-5607-4818-8504-4b4ec54128a0">


## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Manual/Visual testing
2024-07-30 16:35:58 +00:00
Vova Kulikov
eabc522ff0
Svelte: Bump cody web to most recent package @sourcegraph/cody-web (#64152)
The same changes that we did in
https://github.com/sourcegraph/sourcegraph/pull/64149
but for the Svelte version of the app. 

- Update cody web to the `@sourcegraph/cody-web:0.3.0`
- Fix the telemetry name 
- Rendering improvements in cody chat UI
- Change status from experimental to beta

## Test plan
- Manual checks over cody web in the svelte version
2024-07-30 09:11:37 -07:00
Noah S-C
ffb1476841
chore(bazel): re-enable remote caching of Copy{File,Directory,ToDirectory} actions (#64153)
Our remote cache is more stable now, so we may be able to avail of BwoB
better again

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 16:02:11 +00:00
Ara
5ce2eead9a
Adding HTTP Requests support for Azure OpenAI (#64116)
This PR adds special support for http requests to azure OpenAI and
changes special customer configs to use HTTP instead of HTTPS.


## Test plan
Tested this PR locally 
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Vincent <evict@users.noreply.github.com>
2024-07-30 17:45:17 +02:00
Geoffrey Gilmore
7a3da57188
fix/internal/requestclient: read all instances of x-forwarded-for header, not just the first (#64137)
Closes https://linear.app/sourcegraph/issue/SRC-454/extract-and-propagate-user-ip-address-throughout-the-request-lifecycle

According to [HTTP1.1/RFC 2616](https://www.rfc-editor.org/rfc/rfc2616): Headers may be repeated, and any comma-separated list-headers (like `X-Forwarded-For`) should be treated as a single value.

In section 4.2:

>   Multiple message-header fields with the same field-name MAY bepresent in a message if and only if the entire field-value for that header field is defined as a comma-separated list [i.e., #(values)]. **It MUST be possible to combine the multiple header fields into one"field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field-value to the first, each separated by a comma.** The order in which header fields with the same field-name are received **is therefore significant** to the interpretation of the combined field value, and thus a proxy MUST NOT change the order of these field values when a message is forwarded.

For Example:

For the following HTTP request, it's valid to have multiple instances of x-forwarded-for:

| Header Name      | Header Value                |
|------------------|---------------------------|
| X-Forwarded-For  | 203.0.113.195, 70.41.3.18 |
| X-Forwarded-For  | 150.172.238.178           |
| X-Forwarded-For  | 123.45.67.89              |
| ... | ...|

That must be interpret-able as `X-Forwarded-For: 203.0.113.195, 70.41.3.18, 150.172.238.178, 123.45.67.89`

Previously, our code used http.Header.Get():

9e26623d90/internal/requestclient/http.go (L81-L95)

However, [func (Header) Get](https://pkg.go.dev/net/http#Header.Get) only returns the first value of the header:

> Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". ...

In our example, this means that our code would only get `X-Forwarded-For: 203.0.113.195, 70.41.3.18`, which is invalid according to RFC 2616.


## Test plan

There were no unit tests, so I added some.

## Changelog

<!-- OPTIONAL; info at https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c -->
2024-07-30 08:35:23 -07:00
Vova Kulikov
c8fd001892
Bump cody web to most recent package @sourcegraph/cody-web (#64149)
A few things this PR does
- Update cody web to the most updated version and package name which is
(`@sourcegraph/cody-web`)
- Support custom telemetry name for cody web events (on dotcom it should
be `dotcom.web` and `server.web` on the enterprise instance
- The most updated release of Cody Web includes
   - fixes for remote LLM models on enterprise 
   - improvements for performance rendering Chat UI
   - telemetry fixes

## Test plan
- Manual checks over Cody Web chat UI (standalone chat page and the blob
UI side panel chat)
2024-07-30 12:34:43 -03:00
Geoffrey Gilmore
e74a4d4eba
feat/worker/permission syncing: make sub repo permissions re-insertion fall back to original paths if ips not added yet (#64086)
Closes https://linear.app/sourcegraph/issue/SRC-453/modify-the-perforce-authorization-provider-to-support-ip-aware-sub

This PR builds on https://github.com/sourcegraph/sourcegraph/pull/64010, and enhances the re-insertion logic.

Before, we'd fail the sync operation outright if we tried to re-insert existing permissions that hadn't been converted from the path only form to the (ip, path) tuple.

Now, when trying to reinsert the existing permissions:

- if it has already been converted (`(path, ip)`) -> we save it back in the database using the UpsertWithUP() method
- if it hasn't been converted (`path` only) -> we save it back in the databse using the existing old plain Upsert method

I accomplish this by using a small interface that encpasulates the data and the insertion logic to use:

```go
type subRepoPermissionsUpserter interface {
	// UpsertWithSpec inserts or updates the sub-repository permissions with the data
	// stored in the upserter.
	UpsertWithSpec(ctx context.Context, store database.SubRepoPermsStore, userID int32, spec api.ExternalRepoSpec) error
}

type ipBasedPermissions struct {
	perms *authz.SubRepoPermissionsWithIPs
}

func (u *ipBasedPermissions) UpsertWithSpec(ctx context.Context, store database.SubRepoPermsStore, userID int32, spec api.ExternalRepoSpec) error {
	return store.UpsertWithSpecWithIPs(ctx, userID, spec, *u.perms)
}

type pathBasedPermissions struct {
	perms *authz.SubRepoPermissions
}

func (u *pathBasedPermissions) UpsertWithSpec(ctx context.Context, store database.SubRepoPermsStore, userID int32, spec api.ExternalRepoSpec) error {
	return store.UpsertWithSpec(ctx, userID, spec, *u.perms)
}

var (
	_ subRepoPermissionsUpserter = &ipBasedPermissions{}
	_ subRepoPermissionsUpserter = &pathBasedPermissions{}
)
```

Now, any code that deals with inserting sub repo permissions now can deal with a `[]subRepoPermissionsUpserter` without having to care about the exact semantics to use. Our re-insertion logic is also now more robust. 

## Test plan

New unit tests

## Changelog

<!-- OPTIONAL; info at https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c -->
2024-07-30 08:07:37 -07:00
Matthew Manela
b2cd7e5fee
feat(codenav): Add symbol support for the Hack language (#64015)
Adds scip-ctags support for the Hack language.  

Noteworthy items
1. I did not add support for modules since they are [not
supported](https://github.com/slackhq/tree-sitter-hack/issues/70) in the
tree-sitter grammar right now.


## Screenshots

![image](https://github.com/user-attachments/assets/5c75a0c3-4b88-4e20-a2be-82e04a89791c)

## Test plan
- [x] Update unit tests
- [x] Manually validate symbol side bar for indexed commits
- [x] Manually validate symbol side bar for unindexed commits
- [x] Validate symbol search for indexed commits
- [x] Validate symbol search for unindexed commits
2024-07-30 10:46:00 -04:00
Geoffrey Gilmore
70b31c9be7
feature/worker/permission syncer: perforce: sync HOST field using IP addresses (#64010)
The perforce permission syncer has been adapted to now read and save the HOST field from the perforce protections table, which contains the IP address(es) that the path rule that it applies to.  It uses the updated sub_repository_rules store methods introduced in https://github.com/sourcegraph/sourcegraph/pull/63811/.

### Notes

- There is some existing logic in the permissions syncer that attempts to re-insert the existing sub_repo_permissions if we encounter a temporary (timeout, etc.) error when syncing. However, there is an edge case: what do we do if the existing permissions don't have an IP address associated with them yet (they were inserted before the updated permission syncer ran)? For simplicity, in this PR I leaned towawrds correctness - I fail the operation outright (I'd rather temporarirly lock someone out rather than accidentally leak information). I implemented a more robust straetgy for this in https://github.com/sourcegraph/sourcegraph/pull/64086. 


## Test plan

- The existing unit tests have been adapted to use the new authz.SubRepoPermissionsWithIP structs (I use wildcard IP addresses). 


- The big new test to pay attention to is TestScanIPPermissions (and the associated `sample-protects-ip.txt` file). 

## Changelog

- The perforce permissions syncer has been updated to save the IP address associated with each sub_repository_permissions rule.
2024-07-30 07:41:19 -07:00
Jean-Hadrien Chabran
7b0f478d6f
chore(ci): pass --profile to bazel-do jobs (#64148)
Follow-up to [this
comment](https://github.com/sourcegraph/sourcegraph/pull/63910#discussion_r1683190713)
where the need was raised for having profiles for further inspection of
problematic targets when run in isolation.

Basically, every bazel-do will now collect the profile, and it'll be
uploaded as a job artifact.

## Test plan

See https://buildkite.com/sourcegraph/sourcegraph/builds/284913 for a
test run.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 08:01:27 -05:00
Jean-Hadrien Chabran
bc4acd1fbd
feat(local): sg tail (#64146)
This PR brings back https://github.com/sourcegraph/sgtail back in `sg`,
plus a few adjustments to make it easier to use. I'll archive that repo
once this PR lands.

@camdencheek mentioned you here as you've been the most recent beta
tester, it's more an FYI than a request for a review, though it's
welcome if you want to spend a bit of time reading this.

Closes DINF-155

## Test plan

Locally tested + new unit test + CI

## Changelog

- Adds a new `sg tail` command that provides a better UI to tail and
filter log messages from `sg start --tail`.
2024-07-30 14:03:27 +02:00
Christoph Hegemann
62b4718bd9
chore(syntax-highlighter): Some cleanup for locals detection (#64144)
1. Use interned strings for scope kinds
This lets us avoid a few String allocations and requires dealing with
fewer lifetimes/borrows
2. Unify tree walks to use `Ancestors`
This means we now consistently apply the fuel limit (we were missing a
few loops before)
3. Use binary search over linear search to find preceding defs
Silly me
4. Removes hacks for skipping entries in the scope tree
We now make sure to never insert references that ought to be skipped in
the first place

I'd recommend reviewing commit by commit, the changes aren't really
related. Just didn't want to spam PRs for this.

## Test plan

Snapshots continue to pass. Verified fuel limit is enforced by creating
loopy trees on purpose. Ran some hyperfines on spring-framework to make
sure perf didn't regress.
2024-07-30 12:02:45 +02:00
William Bezuidenhout
16d1ab7586
chore(log): remove use of log15 in ghe-feeder (#64131)
update ghe-feeder to use sourcegraph/log. As a consequence ghe-feeder no
longer has the logFile flag - instead people should just redirect the
output to a file with >> / >

Closes DINF-153

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
CI
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 11:31:38 +02:00
Rafał Gajdulewicz
963527ccd9
Support detecting search and edit intent (#64129)
Support detecting `search` and `edit` intents - return additional scores
for those two categories.

## Test plan

- tested locally -> use `{
  chatIntent(query: "yo", interactionId: "123") {
    intent
    score
    searchScore
    editScore
  }
}
` as GraphQL payload
2024-07-30 09:20:45 +00:00
William Bezuidenhout
9898262143
ci: automatic retry push images job at least 1 (#64145)
Closes DINF-154

## Test plan
CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-30 09:32:03 +01:00
Craig Furman
d945f19285
feat(appliance): self-update can update multiple deployments (#64132)
The helm chart will configure both the backend and frontend deployments
to self-update:
https://github.com/sourcegraph/deploy-sourcegraph-helm/pull/513

Relates to
https://linear.app/sourcegraph/issue/REL-302/self-update-should-update-appliance-frontend-too
2024-07-30 08:30:26 +00:00
Craig Furman
ebec72d7ed
fix(appliance): do not deploy in dev mode by default (#64097)
In the first UI, dev mode was a webform field. On reflection, it's
probably simpler as an env var, since it is not expected that production
users will enable this.
2024-07-30 09:20:34 +01:00
Christoph Hegemann
1a1d68cb74
codeintel: document that pagination for usages might return extra results (#64142)
I'm not actually sure if I can even guarantee the _at least_ part for
syntactic usages right now. It would require particularily pathological
circumstances, but because I have to stay within the given
`context.Context` window, I might end up returning fewer syntactic
results than requested.

I think that should be fixable in the future so I'd still like the spec
to reflect the state we'd like to end up at.

## Test plan

Just a documentation/specification change
2024-07-30 06:43:41 +02:00
Varun Gandhi
3f0a85219c
chore: Move codenav types to lower-level package (#64141)
For the implementation of precise usagesForSymbol, I need to be
able to access some of these types in the codenav package directly, so move
a bunch of types there to avoid an import cycle: codenav -> resolvers -> codenav.
2024-07-30 12:25:11 +08:00
Anish Lakhwara
8c2d8da234
fix(appliance): don't include is_development builds in list of versions (#64138)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
@DaedalusG was running into warnings in the console due to the
releaseregistry containing 2 entries for v5.4.0 (one was a development
build)
We're now filtering those

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Manual testing

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- fix(appliance): don't allow installation of development builds
2024-07-29 17:39:15 -07:00
Chris Smith
caa4301bcb
Remove references to modelconfig.sourcegraph.pollingInterval (#63956)
As the next release of Sourcegraph approaches, and we get our ducks in a
row for rolling out the modelconfig changes, we have cut the ability for
the Sourcegraph backend to poll Cody Gateway for new LLM models.
Instead, if configured to, the only "Sourcegraph-supplied models" will
be what is embedded into the binary at build-time. (See
`internal/modelconfig/embedded`.)

This PR removes any externally facing references to this capability.
Since it wasn't actually implemented yet, this isn't actually going to
change any functionality.

We'll add this capability in the next release, ~September. See
[PRIME-290](https://linear.app/sourcegraph/issue/PRIME-290/feature-sourcegraph-instances-can-automatically-pick-up-new-llms).

## Test plan

NA

## Changelog

NA
2024-07-29 23:20:24 +00:00
Warren Gifford
a01ebad841
bug(appliance): parse v in target versions (#64139)
This just parses the version string such that it can later be correctly
applied to the config when installing a fresh SG

## Test plan
Tested locally

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 23:17:52 +00:00
Robert Lin
38d4e83e59
feat/requestclient: propagate original User-Agent as X-Forwarded-For-User-Agent (#64113)
Propagates a for-reference-only record of the first `User-Agent` seen
when a request gets into Sourcegraph across services and contexts. This
allows telemetry to try and indicate where a request originates from
(https://github.com/sourcegraph/sourcegraph/pull/64112), rather than
only having the most recent user-agent.

A new header and `requestclient.Client` property
`X-Forwarded-For-User-Agent` and `ForwardedForUserAgent` is used to
explicitly forward this. Strictly speaking I think we're supposed to
just forward `User-Agent` but it looks like in multiple places we
add/clobber the `User-Agent` ourselves.

The gRPC propagator currently sets user-agent on outgoing requests, this
change also makes that consistent with the HTTP transport, such that
both only explicitly propagate `X-Forwarded-For-User-Agent`

## Test plan

Unit tests
2024-07-29 14:17:25 -07:00
Jason Hawk Harris
e0fa2bd66e
SvelteKit: fix issue where clicking link with no href refreshed the page (#64136)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
When clicking a menu item with no href, page refreshed every time. Now,
menu items with no href cause no action when clicked.


https://github.com/user-attachments/assets/abcc5164-64fa-4b37-8f8c-7df110bca23e

This is a follow up to this PR:
https://github.com/sourcegraph/sourcegraph/pull/64134

## Test plan
Manual/Visual testing
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 19:57:49 +00:00
Jason Hawk Harris
288a7b6b83
SvelteKit: Add 'Tools' Menu item back to global navigation (#64134)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
This PR adds the `Tools` Menu Item back to the Global Navigation Bar of
the svelte-kit web app, and removes the sub menus for both `Code Search`
and `Cody` menu items.

Before:
![Screenshot 2024-07-29 at 11 45 12
AM](https://github.com/user-attachments/assets/b7d5a42c-b297-4db0-9ddc-21231f9b2529)

After: 
![Screenshot 2024-07-29 at 11 44 37
AM](https://github.com/user-attachments/assets/3abcfa1a-7922-4f25-8dbb-efa84698c24c)
 

## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Visual/manual testing
Passing CI

## Changelog
<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 19:33:44 +00:00
Camden Cheek
0a0bb77b3b
Svelte: do not show path section if empty (#64135)
Fixes SRCH-788
2024-07-29 19:06:29 +00:00
Anish Lakhwara
98c6b9703f
feat/Appliance: Frontend Pulls Version Info from RelReg (#64089)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Resolves
[REL-290](https://linear.app/sourcegraph/issue/REL-290/frontend-ui-pulls-sourcegraph-versions-to-install-from-release)
by making a single request to the release registry to get a list of
versions

## Test plan 
manual tested
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

- feat(appliance): frontend pulls versions from relreg
2024-07-29 11:40:25 -07:00
Michael Bahr
ace1d8872e
chore: remove flaky flag from svelte e2e_test (#64123)
Test have been stable since
https://github.com/sourcegraph/sourcegraph/pull/63910. See
https://buildkite.com/organizations/sourcegraph/analytics/suites/sourcegraph-bazel/tests/e143a9fc-8857-83f0-8cfb-03e1c6f48f7b?branch=main

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 08:54:53 -06:00
Noah S-C
878931fceb
chore(ci): emit execlog for image push jobs (#64130)
So we can dig into why stuff is being built

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 14:08:10 +00:00
William Bezuidenhout
4f5793473f
chore(sg): show cloud ephemeral faq (#64127)
* show a link to the FAQ on certain errors
* add FAQ command to open the FAQ page

Closes  DINF-150
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
Locally
```
⚠️ Triggering Cloud Ephemeral builds from "main" is not supported.

  Alternatively, if you still want to deploy "main" you can do:

  1. create a new branch off main by running  git switch <branch-name>
  2. push the branch to the remote by running  git push -u origin <branch-name>
  3. trigger the build by running  sg cloud ephemeral build

  FAQ https://www.notion.so/sourcegraph/How-to-deploy-my-branch-on-an-ephemeral-Cloud-instance-dac45846ca2a4e018c802aba37cf6465?pvs=4#20cb92ae27464891a9d03650b4d67cee
```

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 15:58:51 +02:00
Michael Bahr
e8c1ffeef5
fix: add commit signing filter to credentialForGitHubAppExists (#64128)
This is a follow up to
https://github.com/sourcegraph/sourcegraph/pull/64120 so that it doesn't
mix up alerts between commit signing and code hosts for site admins.

## Test plan

Manual testing + CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 13:52:06 +00:00
Christoph Hegemann
195b8b3aed
scip-syntax: Simplifies to two visibilities (#64124)
Closes
https://linear.app/sourcegraph/issue/GRAPH-774/see-if-we-can-get-away-with-2-visibilities-in-scip-syntax

## Test plan
Snapshots don't change

A couple hyperfine runs suggest this is also slightly quicker

```
spring-framework on  HEAD (9409543) [?]
❯ hyperfine --warmup 3 'git archive HEAD | scip-syntax index tar - -l java' 'git archive HEAD | scip-syntax-main index tar - -l java'
Benchmark 1: git archive HEAD | scip-syntax index tar - -l java
  Time (mean ± σ):     909.9 ms ±   9.7 ms    [User: 7307.6 ms, System: 212.2 ms]
  Range (min … max):   902.4 ms … 935.2 ms    10 runs

Benchmark 2: git archive HEAD | scip-syntax-main index tar - -l java
  Time (mean ± σ):     939.6 ms ±   6.5 ms    [User: 7681.2 ms, System: 210.9 ms]
  Range (min … max):   931.2 ms … 952.1 ms    10 runs

Summary
  git archive HEAD | scip-syntax index tar - -l java ran
    1.03 ± 0.01 times faster than git archive HEAD | scip-syntax-main index tar - -l java

spring-framework on  HEAD (9409543) [?]
❯ hyperfine --warmup 3 'git archive HEAD | scip-syntax index tar - -l java' 'git archive HEAD | scip-syntax-main index tar - -l java'
Benchmark 1: git archive HEAD | scip-syntax index tar - -l java
  Time (mean ± σ):     916.4 ms ±  10.7 ms    [User: 7302.7 ms, System: 217.8 ms]
  Range (min … max):   905.4 ms … 939.9 ms    10 runs

Benchmark 2: git archive HEAD | scip-syntax-main index tar - -l java
  Time (mean ± σ):     945.4 ms ±   7.9 ms    [User: 7684.8 ms, System: 212.6 ms]
  Range (min … max):   935.0 ms … 959.3 ms    10 runs

Summary
  git archive HEAD | scip-syntax index tar - -l java ran
    1.03 ± 0.01 times faster than git archive HEAD | scip-syntax-main index tar - -l java
```
2024-07-29 15:34:56 +02:00
Keegan Carruthers-Smith
26e84a0aa4
gomod: update zoekt to include improvement to experiment (#64125)
This includes a commit which hopes to improve the performance of a
recent experiment to improve guardrails performance.

12ce07a298...ebb3ca2424

- https://github.com/sourcegraph/zoekt/commit/04e7057ffe Enabling
numContextLines in non-json format
- https://github.com/sourcegraph/zoekt/commit/ebb3ca2424 index: use a
random sample of ngrams when limiting

Test Plan: CI

Part of
https://linear.app/sourcegraph/issue/CODY-3029/investigate-performance-of-guardrails-attribution-endpoint
2024-07-29 13:10:34 +00:00
Stefan Hengl
5d4d003107
fix(search_jobs): prevent job state flip-flopping between 'queued' and 'processing' (#64098)
Fixes SPLF-170

This fixes a bug in our status reporting where we would report a job as
"queued" although it should be reported as "processing". In some cases
this led to the state flip-flopping between "queued" and "processing".

This happens, for example, if a worker has just finished a repo-rev job
(and set it to completed) but hasn't yet dequeued a new job. In this
brief period we reported the entire search job as queued.

Test plan:
- updated unit test
- manual testing

I ran the following search job which previously exhibited this behavior
and verified that now it doesn't.
```
context:global r:^github\.com/sourcegraph/sourcegraph$@*refs/heads/* ghp_.+ patterntype:regexp
```
2024-07-29 14:57:12 +02:00
Michael Bahr
67c9a09059
fix: connection pending alert and alert content alignment (#64120)
When there is already a global token, then the notice after installing a
personal app is wrong. This PR handles this issue, so that the notice
shows up as expected.

We also fix an alignment issue, where the call to refresh the page would
be in a distinct column, instead of what we'd expect.

## Test plan

Manual testing

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-29 07:46:23 -05:00
Varun Gandhi
963792f36e
chore: Bubble precise Usages instead of Locations (#64118)
This patch changes the code so that the core APIs we need
for precise usagesForSymbol actually return (Upload)Usages instead
of just (Upload)Locations, so that we have the usage kind information
as well as the symbol names available. I will be handling the GraphQL
layer for converting the Usages to appropriate Resolvers in a follow-up PR.

## Test plan

Modified a bunch of existing mock tests. 🤷🏽
2024-07-29 20:12:23 +08:00
Christoph Hegemann
cf5bc9f48e
observability: Adds useful data to traces from gosyntect.Highlight (#64121)
This might help with debugging in the future.

## Test plan

N/A
2024-07-29 14:07:01 +02:00
Jacob Pleiness
7e82c27ab5
feat(appliance): add wait for admin state (#64042)
Add basic health check to switch state to `waitForAdmin` after
Sourcegraph frontend is ready. As noted in the code, this is a temporary
health check and will/should be replaced with something more
comprehensive in the near future.

Wait for admin page successfully appears when Sourcegraph frontend is
"ready":

Co-authored-by: Jacob Pleiness <jdpleiness@users.noreply.github.com>
Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-29 11:21:55 +01:00
Keegan Carruthers-Smith
e02bd3d025
search-blitz: adjust limit for snippetAttribution to match gateway (#64119)
Cody doesn't set a limit, so we use the default that Cody Gateway sets.
It uses a value of 4.

Test Plan: yolo
2024-07-29 12:10:11 +02:00
Christoph Hegemann
3f8620508b
codeintel: Speed up syntactic and search-based usages using batch APIs (#64078)
Closes
https://linear.app/sourcegraph/issue/GRAPH-771/chunk-syntactic-usage-tasks-and-use-batch-apis-to-handle-chunks

This is the last step for properly implementing #63971. We split the
`candidateFiles` search produces into chunks and process these in
parallel using the new batch api on `MappedIndex`.

## Test plan
Existing tests continue passing

---------

Co-authored-by: Varun Gandhi <varun.gandhi@sourcegraph.com>
2024-07-29 04:09:05 +02:00
Noah S-C
51cf4dcba8
fix(ci): reduce push_all concurrency even further due to ratelimits (#64111)
😢 

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-26 19:13:27 +01:00
Jason Hawk Harris
b212aff5dd
Svelte Navigation: hide teams when own is not enabled (#64110)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Teams option in the user menu will be hidden when own is not enabled. 

Own Enabled: 
![Screenshot 2024-07-26 at 11 54 50
AM](https://github.com/user-attachments/assets/1f095fa4-bbb7-416c-89aa-6e79bbc02756)

Own Not Enabled: 
![Screenshot 2024-07-26 at 11 54 25
AM](https://github.com/user-attachments/assets/e87c7dd8-fdeb-4a11-9688-7d39df972f8a)

## Test plan
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Visual/Manual testing

## Changelog
<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-26 10:25:41 -07:00
Keegan Carruthers-Smith
e54cf18f58
gomod: update zoekt for guardrails perf experiment (#64109)
This only contains one commit which has a performance improvement
experiment hidden behind an environment variable.

- https://github.com/sourcegraph/zoekt/commit/12ce07a298 index:
experiment to limit ngram lookups for large snippets

Test Plan: CI
2024-07-26 16:28:10 +00:00
Jason Hawk Harris
a8b3e8e7f5
Blob search: Fix incorrect icons in the blob search bar (#64108)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Switch from Lucide icons to MDI which look better in this case. 

Before:
![Screenshot 2024-07-26 at 10 58 55
AM](https://github.com/user-attachments/assets/a0ee0f72-9c32-41c4-be7b-88eb050eaa1a)

After: 
![Screenshot 2024-07-26 at 10 58 41
AM](https://github.com/user-attachments/assets/6834c1a2-bd8e-4b6d-8229-f2f3dc1daa62)


## Test plan
Manual/Visual testing
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-26 11:19:03 -05:00
James Cotter
d2dd9ac454
msp/deploy: remove old author variable (#64107)
Leftover that somehow slipped through 🤦🏻 

## Test plan
CI
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
2024-07-26 16:56:53 +01:00
James Cotter
20664df7fc
msp/deploy: use BUILDKITE_BUILD_CREATOR as fallback (#64104)
If a build is triggered from the web the variable BUILDKITE_BUILD_AUTHOR
is not set which the msp_deploy.sh script requires. This PR uses
BUILDKITE_BUILD_CREATOR as a fallback if _AUTHOR is missing

## Test plan
Tested locally
2024-07-26 15:51:09 +01:00
Noah S-C
59a0d15eab
fix(ci): reduce push_all concurrency due to ratelimits (#64106)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-26 14:44:23 +00:00
Vincent
2333ddeaab
fix: add extra check for code intelligence inference (#64083) 2024-07-26 15:22:52 +01:00
Erik Seliger
d249b8f701
gerrit: Add support for repositoryPathPattern (#64102)
Most other code host connections we support have this property to
control the generated name, but for some reason it was forgotten for
Gerrit.

This PR adds it, plus a few tests.

![Screenshot 2024-07-26 at
14.04.35@2x.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/Xvbrpl1hwVbe4tb9QeLp/6b7f2e35-1147-4e6d-912c-628ea94f2f33.png)

Test plan: Added tests, cloned a gerrit repo locally.

## Changelog 

Added support for the `repositoryPathPattern` setting for Gerrit code
host connections.
2024-07-26 15:08:14 +02:00
Michael Bahr
3ff0ddf1cb
fix(batches): switch github app installation handling from redirect flow to webhooks (#64036)
Closes SRCH-741
Closes SRCH-716

This PR removes the GitHub installation code from the redirect flow to a
webhook-based appraoch. We expect that the GitHub server calls the
webhook when the installation is ready, and therefore shouldn't see the
errors explained in the issues above.

To handle the potential delay until the webhook is called and the
credential is set up, I added a scrappy info notice that the user should
refresh their page:

<img width="928" alt="Screenshot 2024-07-24 at 13 48 24"
src="https://github.com/user-attachments/assets/4d298f2a-d7b8-423b-9e2f-2ae53fbce1ac">

Below is what you see after you refreshed (or if the webhook was called
faster than the user being redirected back to the settings):

<img width="929" alt="Screenshot 2024-07-24 at 13 50 14"
src="https://github.com/user-attachments/assets/b6826158-8561-476d-b20e-e36f8cfb86fd">

I'm able to create PRs for sourcegraph-testing with an app that was
created this way.

<img width="1171" alt="Screenshot 2024-07-24 at 16 16 06"
src="https://github.com/user-attachments/assets/86e20acb-136f-4a46-a33b-bdfdd0d51d71">

I'm seeing an error when getting an access token with a personal github
app to run a batch change, but that will be handled with another PR.

<img width="1053" alt="Screenshot 2024-07-24 at 16 38 38"
src="https://github.com/user-attachments/assets/5655ba91-1ae4-453a-8d5c-1bcdbe34bc17">

## Test plan

Manual testing locally, and more testing to be done on S2 where we have
a more production like environment

## Changelog

- When installing a GitHub app for batch changes, the instance now waits
for a callback from GitHub to complete the installation to avoid issues
from eventual consistency.

---------

Co-authored-by: Peter Guy <peter.guy@sourcegraph.com>
2024-07-26 11:53:34 +00:00
Varun Gandhi
6d981c60ad
chore: Update main occurrence extraction code to allow for symbol-based matching (#64082)
At the heart of the loop for extracting usages across a Sourcegraph
instance is the `extractLocationsFromPosition` function, which
extracts related symbols and source ranges from a single SCIP
Document. (Source ranges for returning to the user directly,
and related symbols to do further lookups, e.g. in the case
of inheritance.)

Since we want to perform matching based on symbol names in the upcoming
precise usagesForSymbol API, and also return symbol names for each
associated source range, this function needs to be updated to:
1. Be able to take a symbol name for doing lookups. This is done using
    the new `FindUsagesKey` type which allows two cases - position-based and
    symbol-based.
2. Be able to return symbol names associated with every source range.
    This is done by creating a new `UsageBuilder` type which somewhat subsumes
    the `Location` type. We avoid copying the same 'UploadID' and 'Path'
    fields eagerly for clarity; that will be handled by callers in the future when
    they mix `UsageBuilder` values across different Documents (by first calling `build`).

For the above, I've introduced a new func `extractRelatedUsagesAndSymbolNames`,
and `extractLocationsFromPosition` delegates to that. In the future,
`extractLocationsFromPosition` will be removed.
2024-07-26 18:28:43 +08:00
Petri-Johan Last
64ac259ab5
[fix] Fix being unable to add batch changes credentials when rate limited (#63984) 2024-07-26 11:07:59 +02:00
Stefan Hengl
590b7e2b01
chore(frontend): use explicit cache for admin analytics (#64077)
Relates to #64041

This refactors the `adminanalytics` package to set the cache explicitly
instead of implicitly relying on the global `redispool.Store`. The
global store obfuscated the dependency and also made testing a bit
awkward.

Test plan:
- new unit test
- I ran a local instance and checked for panics in the logs from the
worker job that updates the cache on startup.
- Checked that the following GQL query returned results 

```GQL
query {
  site {
    analytics {
      search(dateRange: LAST_MONTH, grouping: WEEKLY) {
        searches {
          nodes {
            date
            count
          }
          summary {
            totalCount
            totalUniqueUsers
            totalRegisteredUsers
          }
        }
      }
    }
  }
}
```
- I deleted the cache and ran the GQL query again and verified that
cache had the following new entries
```
1) "adminanalytics:Search:Searches:LAST_MONTH:WEEKLY:nodes"
2) "adminanalytics:Search:Searches:LAST_MONTH:WEEKLY:summary"
```
2024-07-26 10:14:56 +02:00
Warren Gifford
c68e92bc28
Maintenance Splash Page (#64019)
This PR makes a maintenance splash page intended to display service
health after installation completes.
Intended as WIP no nav yet

<img width="973" alt="Screenshot 2024-07-24 at 12 00 44 AM"
src="https://github.com/user-attachments/assets/3e2ecd67-3ef7-4bdc-9f45-d8740eb426f8">

## Test plan
Run local Golden Tests

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-25 16:23:22 -07:00
Anish Lakhwara
3814fd7390
feat(appliance): Merge unstructured objects from helm serialization and appliance cfg defaults (#64021)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
This PR implements [this
comment](https://linear.app/sourcegraph/issue/REL-218/ingressservice-consistency-for-helm-deployment#comment-6e1b88b5)
from
[REL-218](https://linear.app/sourcegraph/issue/REL-218/ingressservice-consistency-for-helm-deployment).
~~Currently, not included in `reconcileFrontendService` or
`reconcileFronteendIngress`. It's still a **work in progress**,
requesting review to make sure I'm on the right path, the test doesn't
currently pass.~~
Got the tests to pass locally, and added them to
`reconcileFronteendService` and `reconcileFronteendIngress`, however,
I'd like to deploy this locally with helm to ease my concern in it
breaking.

~~This PR alone isn't enough to close REL-218 either, we'll need
something like @craigfurman's [PR in
deploy-sourcegraph-helm](https://github.com/sourcegraph/deploy-sourcegraph-helm/pull/509)
as well~~
This PR no longer requires that helm values be serialized, since we
adopt the object that exists in k8s rather than reading serialized helm
values.

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Unit tests included

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- feat/appliance: Include existing objects when constructing Frontend's
`Service` & `Ingress`

---------

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-25 22:30:14 +00:00
Robert Lin
18313d5442
fix/telemetry: silence invalid events that we already know about (#64084)
Adds a read-only "known baddies" list of feature/action combination
where we know the event will produce marshalling or validation errors,
and skips the error-logging step.

Note that the code fails the entire batch the way it works today, but in
practice, none of our clients batch events yet, so this is something to
fix when we start doing that.

## Test plan
```
sg start enterprise
```

```gql
mutation {
  telemetry {
    recordEvents(
      events: [{feature: "cody.completion", action: "persistence:present", source: {client: "VSCode.Cody", clientVersion: "0.14.1"}, parameters: {version: 0, privateMetadata: 12}}]
    ) {
      alwaysNil
    }
  }
}
```

get an error response, but does not record a log in `sg start` output
2024-07-25 14:14:04 -07:00
Anton Sviridov
7e5b52ea67
Syntactic indexing policy toggle: UI and supporting APIs (with backcompat) (#64075)
Fixes GRAPH-751
Fixes GRAPH-636

Reverts sourcegraph/sourcegraph#64046 which itself was a revert of
https://github.com/sourcegraph/sourcegraph/pull/63876 due to backwards
compatibility concerns.

This new PR adds two extra commits which restore the `indexingEnabled`
field, and make `syntacticIndexingEnabled` field optional.

---

Fixes GRAPH-636
Fixes GRAPH-751

This PR aims to allow admins to enable syntactic indexing on per-policy
basis using the existing UI and APIs with the following amendments:

- New UI toggle for syntactic indexing – **only visible if the
experimental feature is enabled** (see screenshots below)
- New field in GraphQL API for syntactic indexing
- New Go resolvers to handle the new field

To support this on the backend, we also update the policies handling
code and SQL queries to ensure we can retrieve and update the
`syntactic_indexing_enabled` field.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

- Backend part covered by updated policies tests
- Manual testing of UI

With experimental feature **enabled**:

![CleanShot 2024-07-22 at 12 56
56](https://github.com/user-attachments/assets/e95aa224-be9a-40a6-9e42-6f409478e2fc)

With experimental feature **disabled**:
![CleanShot 2024-07-22 at 12 57
21](https://github.com/user-attachments/assets/0d46a65d-95bc-4695-a3df-ad9aa86dbd36)

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

- In site-admin APIs for updating code intelligence policies:
  - field `indexingEnabled` is renamed to `preciseIndexingEnabled`
- a required `syntacticIndexingEnabled` is added (only takes effect if
experimental feature is enabled)
  - field `forIndexing` is renamed to `forPreciseIndexing`

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-25 20:03:56 +01:00
Noah S-C
5507a4a588
chore(local): use //cmd/frontend:frontend_nobundle for bazel commandsets (#64085)
Changes in client-side code should not result in expensive rebuilds of
`frontend` locally when using bazel with `sg start`. For some reason,
iBazel still thinks it needs to be rebuilt (possibly it uses `query`
instead of `cquery` and therefore doesnt resolve `selects`), but bazel
underneath determines nothing needs to be rebuilt so theres very little
cost

## Test plan

Command set with just `frontend` in a `bazelCommands` section and then
`sg start <command set>`

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-25 16:49:53 +00:00
Anish Lakhwara
9f4c160f91
feat(appliance): implement re-direct on all unknown endpoints (#64059)
Resolves request 4 of
[REL-78](https://linear.app/sourcegraph/issue/REL-78/when-sourcegraph-frontend-is-down-a-user-trying-to-access-sourcegraph#comment-ae562c6d)

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-25 14:41:21 +00:00
Nelson Araujo
49b32fcf3a
Wolfi image for Sourcegraph Frontend (#63798)
Creates the Wolfi image for the Appliance Maintenance UI

## Test plan

```
bazel test \
      //internal/appliance/frontend/maintenance:image_test \
      //docker-images/appliance-frontend:image_test
```
2024-07-25 15:33:49 +01:00
Craig Furman
255e6387cc
feat(appliance): healthchecker manages ingress-facing service (#64043)
**Appliance points ingress-facing service to itself by default**

Not frontend.

**feat(appliance): healthchecker manages ingress-facing service**

Add a new background goroutine to the appliance. It does nothing until a
"begin" channel closes. The idea is that another part of the appliance
will close this channel if the configmap state is set to a post-install
value (or on startup if this is already the case when an appliance
boots).

After this barrier is lifted, the healtchecker periodically checks the
readiness (using k8s conditions) of each pod returned by the frontend
deployment's label selector. If even a single pod is ready, it ensures
that the service points to frontend. Otherwise, it waits for a grace
period, checks again, and if downtime persists, it points the service to
the appliance.

This should cover the following cases:
- The service is pointed to frontend after the admin clicks "go" after
  an initial successful install.
- The service is pointed to appliance after frontend downtime that
  exceeds the grace period.
- The service is promptly pointed to frontend after downtime ends.
2024-07-25 14:40:10 +01:00
Christoph Hegemann
a4c7e9be9a
scip-syntax: uses .starts_with to check reference capture (#64081)
Sorry missed this during the review. No need to allow `rEfErEnCe` as the
capture name. Noticed this while checking the samply profile and seeing
string allocations (gets us back 20ms on spring-framework 🎉)

## Test plan

Covered by existing tests
2024-07-25 13:05:12 +00:00
Noah S-C
1069817b5b
chore(bazel): rework push_all to improve concurrency by avoiding bazel server lock (round 2) (#64079)
Second attempt at https://github.com/sourcegraph/sourcegraph/pull/64044,
now that rate limit is set right. So lets boost the concurrency to all
cores!

## Test plan

main dry-run
https://buildkite.com/sourcegraph/sourcegraph/builds/284268#0190e9cf-b902-4f7c-a1ad-fca8700b8fa0

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-25 12:59:43 +00:00
Varun Gandhi
cadb6d8e70
chore: Unify LsifStore.*SymbolUsages APIs into one (#64076)
For precise usagesForSymbols, we want to propagate usages everywhere
(with associated symbol names, not just 'Location' values). This PR
introduces the new Usage type, and unifies the old GetBulkSymbolUsages and
GetMinimalBulkSymbolUsages APIs into a single GetSymbolUsages API.

We convert the Usage values to Location to avoid changing a lot of code
at once.

We also change the DB query to do grouping and aggregation for us
instead of doing it in Go code.

---------

Co-authored-by: Christoph Hegemann <christoph.hegemann@sourcegraph.com>
2024-07-25 20:45:47 +08:00
YK
09bd207693
Update the outdated link to #dev-experience to #discuss-dev-infra (#64018)
## Test plan

Test each link manually.

---------

Co-authored-by: Bolaji Olajide <25608335+BolajiOlajide@users.noreply.github.com>
2024-07-25 06:58:22 -05:00
Bolaji Olajide
20b858f6c3
fix(build-tracker): Failed back-compat doesn't count towards branch-locking quota (#63911)
Closes
[DINF-51](https://linear.app/sourcegraph/issue/DINF-51/failed-back-compat-doesnt-count-towards-branch-locking-quota)

## Context

If a back-compat step on main fails, the build is marked as having
failed. However, we don't treat that as a failure in build-tracker,
resulting in no #buildkite-main post and not counting towards failed
build quota for locking main.

The reason why this was happening is that the Backcompat build wasn't
linked to the main Sourcegraph build in anyway. However, when a
backcompat fails the main build reflects the status of this failure, but
we do not use this field when determining the status of a build, so it
doesn't work for our use case.

![CleanShot 2024-07-18 at 15 04
15@2x](https://github.com/user-attachments/assets/9553330a-ad98-45cc-b4ce-03a22ca1b99d)

We [instead do a walkthrough of all the jobs associated with a build to
figure
out](https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/dev/build-tracker/main.go?L349-372)
if the build has failed, fixed or is passing.

With this logic, it means we have to link the steps from child builds
that a particular build triggers to it's parent.

## Test plan

* Create a build that'll have backcompat failing
* The build tracker event associated with the main build will be
reported with a state of failed to buildkite.

![CleanShot 2024-07-18 at 15 10
45@2x](https://github.com/user-attachments/assets/1bf503ab-0020-47bf-9512-b3a9ee5d4e36)


## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-25 06:45:09 -05:00
Anton Sviridov
b84636fb55
Syntactic indexing non local refs java (#63822)
Fixes GRAPH-649

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

This PR adds non-local references support to Java (and more generally to
our locals handling code).

The main idea is to cherrypick nodes that _can_ contain global or
resolved (see below) references, handle them first, and then mark
everything else as locals.

- Pure Global references are formed from types of definitions that
_can't_ be locals in our code. Currently it's only methods in Java that
we treat as always global references

- Pure local references - these references should only be resolved
against the locals scope tree and definitions within it - never emitting
a non-local references

- Resolved references - these are first resolved as locals, and if that
doesn't succeed, a global reference is emitted. These will be used most
frequently, as TS grammars don't carry enough information for us to
identify more pure global references. For example, in Java's type bounds
`class Hello<N extends Number>`, Number can refer to both the local type
parameter of an enclosing class (in which case we should emit a local
reference), or it can refer to `java.lang.Number` (in which case we
should emit a global reference)

## Test plan

- New snapshot results
- New evaluation results

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Christoph Hegemann <christoph.hegemann@sourcegraph.com>
2024-07-25 11:44:26 +01:00
Christoph Hegemann
77fbfbda16
codeintel: Adds a batch api for fetching multiple documents to MappedIndex (#64073)
Closes
https://linear.app/sourcegraph/issue/GRAPH-770/batch-api-for-mappedindex

Depends on #64024 

## Test plan

Added unit test
2024-07-25 10:32:59 +02:00
Stefan Hengl
53806cb555
chore(worker): move refreshAnalyticsCache to worker (#64041)
This moves the `refreshAnalyticsCache` job from `frontend` to `worker`

Notes:
the `adminanalytics` package uses a global cache which made testing
awkward. That's why I introduced the `store()` abstraction to swap the
store at test time.

## Test plan
- new unit test
2024-07-25 10:14:01 +02:00
Christoph Hegemann
f7688ff5cb
codeintel: allows batch retrieval of SCIP documents (#64024)
Closes
https://linear.app/sourcegraph/issue/GRAPH-766/batch-api-for-fetching-scip-documents

## Test plan
Tested by being used for the single-path retrieval path, will be tested
more once its used in follow-up PRs with more batching
2024-07-25 08:04:15 +00:00
Christoph Hegemann
e0502149cc
codeintel: returns surroundingContent from search result (#64022)
Closes
https://linear.app/sourcegraph/issue/GRAPH-765/use-surroundingcontent-returned-from-the-search-client

The primary reason for doing this is to avoid sending a bunch of extra
calls for file contents to gitserver, which dominate the profile/trace
after implementing the remaining opts from
https://github.com/sourcegraph/sourcegraph/pull/63971

Also limits the API to only return the line containing the match for now
as discussed with Camden.

We might need to bring back the `lineGetter` for precise usages, but it
should be easy enough to revive at that point /cc @varungandhi-src

## Test plan

Updated unit tests, some manual testing in the API console
2024-07-25 09:50:33 +02:00
Varun Gandhi
2644e24244
fix: Fix Chrome stack overflow during highlighting (#64072)
Using the spread operator with large arrays can trigger a
stack overflow in Chrome/V8. For example, see:
- https://github.com/nodejs/node/issues/16870

In a highlighting context, we can have 10k-100k occurrences
in a file, so let's avoid using the spread operator.

Fixes https://linear.app/sourcegraph/issue/GRAPH-772

## Test plan

Manually tested against sample file.

![](https://github.com/user-attachments/assets/e096c664-063e-44ed-a991-72629af36651)

## Changelog

- Fixes a Chrome-specific stack overflow when highlighting large files.
2024-07-25 11:50:03 +08:00
Warren Gifford
15036143bc
bug/release: update version consts in updatecheck handler (#64052)
update version consts in updatecheck handler, temp solutions

see:
https://linear.app/sourcegraph/issue/REL-145/release-tie-release-consts-to-release-registry

## Test plan
No test

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 20:32:10 -07:00
Craig Furman
29fc613c37
chore(appliance): expose status in config package (#64032)
So that other appliance subpackages (notably reconciler) can import it
without risking a circular dependency.

Relates to
https://linear.app/sourcegraph/issue/REL-78/when-sourcegraph-frontend-is-down-a-user-trying-to-access-sourcegraph
but does not close it. Bottom of a stack, likely more PRs incoming
today.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

This is a refactor, all tests continue to pass.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 16:09:09 -04:00
Noah S-C
c016ce08c1
Revert "chore(bazel): rework push_all to improve concurrency by avoiding bazel server lock" (#64051)
Reverts sourcegraph/sourcegraph#64044

Dockerhub cant handle it and keeps ratelimiting us

## Test plan

CI
2024-07-24 19:33:21 +00:00
William Bezuidenhout
0309564f93
ci: make internal+promote release higher priority in runtypes (#64049)
With the https://github.com/sourcegraph/sourcegraph/pull/63985/files
PatchRelease is matched before InternalRelease leading to the wrong
build being generated.

We therefore move the Promote and Internal Release runtypes higher in
priority so that they get matched first.

## Test plan
```
export RELEASE_INTERNAL=true
export VERSION="5.5.2463"
go run ./dev/sg ci preview
```
👇🏼 
```
go run ./dev/sg ci preview
⚠️ Running sg with a dev build, following flags have different default value unless explictly set: skip-auto-update, disable-analytics
If the current branch were to be pushed, the following pipeline would be run:
  Parsed diff:
  changed files: [WORKSPACE client/web-sveltekit/BUILD.bazel client/web-sveltekit/playwright.config.ts client/web-sveltekit/src/lib/navigation/GlobalHeader.svelte client/web-
  sveltekit/src/routes/[...repo=reporev]/(validrev)/(code)/page.spec.ts client/web/src/cody/chat/new-chat/NewCodyChatPage.tsx client/web/src/cody/sidebar/new-cody-sidebar/NewCodySidebar.tsx
  client/web/src/cody/sidebar/new-cody-sidebar/NewCodySidebarWebChat.tsx client/web/src/enterprise/batches/settings/AddCredentialModal.tsx
  client/web/src/enterprise/batches/settings/BatchChangesCreateGitHubAppPage.tsx client/web/src/repo/blame/hooks.ts client/web/src/repo/blame/shared.ts cmd/frontend/auth/user.go
  cmd/frontend/auth/user_test.go cmd/frontend/internal/codycontext/context.go cmd/frontend/internal/codycontext/context_test.go deps.bzl dev/ci/push_all.sh dev/ci/runtype/runtype.go go.mod go.sum
  internal/codeintel/uploads/BUILD.bazel internal/codeintel/uploads/internal/background/backfiller/BUILD.bazel internal/codeintel/uploads/internal/background/backfiller/mocks_test.go
  internal/codeintel/uploads/internal/background/commitgraph/BUILD.bazel internal/codeintel/uploads/internal/background/commitgraph/job_commitgraph.go
  internal/codeintel/uploads/internal/background/expirer/BUILD.bazel internal/codeintel/uploads/internal/background/expirer/mocks_test.go
  internal/codeintel/uploads/internal/background/processor/BUILD.bazel internal/codeintel/uploads/internal/background/processor/mocks_test.go internal/codeintel/uploads/internal/store/BUILD.bazel
  internal/codeintel/uploads/internal/store/commitdate.go internal/codeintel/uploads/internal/store/commitdate_test.go internal/codeintel/uploads/internal/store/observability.go
  internal/codeintel/uploads/internal/store/store.go internal/codeintel/uploads/mocks_test.go internal/database/migration/shared/data/cmd/generator/consts.go
  internal/database/migration/shared/data/stitched-migration-graph.json package.json pnpm-lock.yaml schema/schema.go schema/site.schema.json]
  diff changes: "Go, Client, pnpm, Docs, Shell"
  The generated build pipeline will now follow, see you next time!

  • Detected run type: Internal release
  • Detected diffs: Go, Client, pnpm, Docs, Shell
  • Computed variables:
    • VERSION=5.5.2463
  • Computed build steps:
    • Aspect Workflow specific steps
      • 🤖 Generated steps that include Buildifier, Gazelle, Test and Integration/E2E tests
    • Image builds
      • :bazel::packer: 🚧 Build executor image
    • :bazel: Bazel prechecks & build  sg
    • :bazel: BackCompat Tests
    • :bazel:🧹 Go mod tidy
    • Linters and static analysis
      • 🍍:lint-roller: Run sg lint → depends on bazel-prechecks
    • Client checks
      • :java: Build (client/jetbrains)
      • :vscode: Tests for VS Code extension
      • :stylelint: Stylelint (all)
    • Security Scanning
      • Semgrep SAST Scan
    • Publish candidate images
      • :bazel::docker: Push candidate Images
    • End-to-end tests
      • :bazel::docker::packer: Executors E2E → depends on bazel-push-images-candidate
    • Publish images
      • :bazel::packer:  Publish executor image → depends on executor-vm-image:candidate
      • :bazel:⤴️ Publish executor binary
      • :bazel::docker: Push final images → depends on main::test main::test_2
    • Release
      • Release tests → depends on bazel-push-images
      • Finalize internal release

```
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 18:59:58 +00:00
Robert Lin
777f69d8e3
feat/enterpriseportal: ignore context cancellation error in GetCodyGatewayUsage (#64016)
Since this queries BigQuery under the hood, it can be a bit slow, and if
the client cancels there's no need for a Sentry report.

## Test plan

n/a
2024-07-24 11:50:21 -07:00
Beatrix
468a01a3ab
cody-gateway: handle missing Google response (#63895)
- Logs a warning instead of returning an error when the Google response
is missing
- This prevents the API from returning an error when the Google response
is empty, which can happen when Google is not happy with the question
due to safety issues. We will only log a decoder error as error.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

only the log level was updated for empty responses. the function
behavior was not changed.

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

cody-gateway: log missing Google response as warning
2024-07-24 17:58:19 +00:00
Michael Lin
56817a7a9e
Revert "Syntactic indexing policy toggle: UI and supporting APIs" (#64046)
Reverts sourcegraph/sourcegraph#63876
https://sourcegraph.slack.com/archives/CHXHX7XAS/p1721835847010889

### Test plan

CI
2024-07-24 15:59:48 +00:00
Will Dollman
092b8be07f
Unpin openjdk-11 version in blobstore package (#64045)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
We previously pinned the version of openjdk-11 in order to avoid a bad
package signature. This is no longer required.

## Test plan

- CI
- Manually verify updated package

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 16:57:21 +01:00
Noah S-C
14123fcc42
chore(bazel): rework push_all to improve concurrency by avoiding bazel server lock (#64044)
This PR is a second attempt at improving push_all.sh, continuing on from
(and inspired by) https://github.com/sourcegraph/sourcegraph/pull/63391.
As a recap, that PR uses
[--script_path](https://bazel.build/reference/command-line-reference#flag--script_path)
to emit a short bash script for every `oci_push` target, which
essentially does minor setup + invokes the executable as if running
`bazel run`.

While the idea in https://github.com/sourcegraph/sourcegraph/pull/63391
was good, it trades concurrent server locking with an equal amount of
overhead in sequentially building the scripts. By observing the
scripts<b>[1]</b> that it would emit, we can notice a few things:
- The path
`/home/noah/.cache/bazel/_bazel_noah/8fd1d20666a46767e7f29541678514a0/execroot/__main__/bazel-out/k8-fastbuild/bin/`
shows up twice, which is the same path that `./bazel-bin` points at
- The script only `cd`'s to a path, unsets some environment variables,
and then executes the underlying script of the target.

The path can be observed to be a combination of bazel-bin, the target's
package (`//cmd/batcheshelper` in this case), as well as the target with
some extra static strings (`candidate_push` with `push_` prefix and
`.sh{,.runfiles}` suffixes for the script & its runfiles respectively).
Knowing this, and assuming that this is reliably so, we can opt to
recreate this manually instead, saving on the hefty overhead of `bazel
run --script_path`.

The current average times for `Push candidate images` and `Push final
images` are ~7m50s and ~8m30s respectively. While the example
main-dry-run build
[here](https://buildkite.com/sourcegraph/sourcegraph/builds/284041#0190e54a-9aaa-471a-81bf-623fce6ffa45)
isnt fully representative of how much rebuilding is required, it sets a
pretty solid 3m20s baseline.

Note this may break with rules_oci changes, but imo thats a small and
very infrequent cost to pay for cleaner log output + shaving a good
piece of time off.

<details><summary><b>[1]</b> A <code>--script_path</code>
example</summary>

```
#!/nix/store/mqc7dqwp046lh41dhs7r7q7192zbliwd-bash/bin/bash
cd /home/noah/.cache/bazel/_bazel_noah/8fd1d20666a46767e7f29541678514a0/execroot/__main__/bazel-out/k8-fastbuild/bin/cmd/batcheshelper/push_candidate_push.sh.runfiles/__main__ && \
  exec env \
    -u JAVA_RUNFILES \
    -u RUNFILES_DIR \
    -u RUNFILES_MANIFEST_FILE \
    -u RUNFILES_MANIFEST_ONLY \
    -u TEST_SRCDIR \
    BUILD_WORKING_DIRECTORY=/home/noah/Sourcegraph/sourcegraph \
    BUILD_WORKSPACE_DIRECTORY=/home/noah/Sourcegraph/sourcegraph \
  /home/noah/.cache/bazel/_bazel_noah/8fd1d20666a46767e7f29541678514a0/execroot/__main__/bazel-out/k8-fastbuild/bin/cmd/batcheshelper/push_candidate_push.sh "$@"
```

</details> 

## Test plan

Observe a `sg ci build main-dry-run`
[here](https://buildkite.com/sourcegraph/sourcegraph/builds/284041#0190e54a-9aaa-471a-81bf-623fce6ffa45).

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 16:55:09 +01:00
Erik Seliger
4f0b5fad17
Make cody gateway usage worker a periodic routine (#64040)
Adds better observability, and follows more standard patterns. I don't
know why I did it that way a year ago when I implemented this 🤦

Test plan: Code review to find behavior changes that CI cannot cover;
also CI.
2024-07-24 16:16:31 +02:00
Erik Seliger
652b734937
Remove dead collaborators invite code (#64039)
This code isn't used anywhere, so removing it.

Test plan: Go compiler doesn't complain.
2024-07-24 15:51:28 +02:00
Petri-Johan Last
bc036ad2ba
fix(source): Fix issue where worker would crash if a Bitbucket Cloud token couldn''t be refreshed (#64028) 2024-07-24 15:03:37 +02:00
Anton Sviridov
c14f892e9f
Syntactic indexing policy toggle: UI and supporting APIs (#63876)
Fixes GRAPH-636
Fixes GRAPH-751

This PR aims to allow admins to enable syntactic indexing on per-policy
basis using the existing UI and APIs with the following amendments:

- New UI toggle for syntactic indexing – **only visible if the
experimental feature is enabled** (see screenshots below)
- New field in GraphQL API for syntactic indexing
- New Go resolvers to handle the new field

To support this on the backend, we also update the policies handling
code and SQL queries to ensure we can retrieve and update the
`syntactic_indexing_enabled` field.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

- Backend part covered by updated policies tests
- Manual testing of UI

With experimental feature **enabled**:

![CleanShot 2024-07-22 at 12 56
56](https://github.com/user-attachments/assets/e95aa224-be9a-40a6-9e42-6f409478e2fc)

With experimental feature **disabled**:
![CleanShot 2024-07-22 at 12 57
21](https://github.com/user-attachments/assets/0d46a65d-95bc-4695-a3df-ad9aa86dbd36)

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

- In site-admin APIs for updating code intelligence policies:
  - field `indexingEnabled` is renamed to `preciseIndexingEnabled`
- a required `syntacticIndexingEnabled` is added (only takes effect if
experimental feature is enabled)
  - field `forIndexing` is renamed to `forPreciseIndexing`

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 13:57:33 +01:00
Varun Gandhi
2663704fed
chore: Change some APIs to use symbols instead of monikers (#64029)
Monikers carry a bunch of redundant fields which basically consist of
information parsed out of the symbol name. This patch cleans up
some APIs to work with symbol names directly instead of monikers.
2024-07-24 20:11:03 +08:00
Stefan Hengl
51b340847d
chore(worker): move aggregated user stats job to worker (#64033)
This moves the job from `frontend` to `worker`.

Note:
I believe there was a subtle bug in the original code. We only evaluated
the
feature flag on startup, which means that changes of the feature flag
only took effect after a restart.

## Test plan:
new unit test
2024-07-24 13:27:22 +02:00
sourcegraph-buildkite
2f24e0f66b
security: Auto-update package lockfiles for Sourcegraph base images (#63776)
Automatically generated PR to update package lockfiles for Sourcegraph
base images.

Built from Buildkite run
[#283904](https://buildkite.com/sourcegraph/sourcegraph/builds/283904).
## Test Plan
- CI build verifies image functionality

Co-authored-by: Buildkite <buildkite@sourcegraph.com>
2024-07-24 12:15:34 +01:00
Christoph Hegemann
19db59b72c
Removes the old GitTreeTranslator API (#64027)
Following through after #63938 

## Test plan

Existing tests continue to pass
2024-07-24 09:22:42 +00:00
Varun Gandhi
dc7da57edb
chore: Make location fetching queries more uniform (#64026)
This patch changes the location querying code so that:
1. We're populating structures corresponding to SCIP instead of LSIF
   (with "scheme" and "identifier" inside "MonikerData")
2. Avoid repeatedly allocating a constant string 'scip' for the scheme
    only to throw it away later.
3. Makes the two queries and their scanning code more similar for easier
    comparison. When I land precise usagesForSymbol, I will de-duplicate
    some of the scanning code between these two queries.

I have avoided renaming all of the local variables to avoid creating
more noise.

## Test plan

Covered by existing tests.
2024-07-24 11:14:22 +02:00
Will Dollman
9dd901f3c9
Integrate security release approval into release pipeline (#63990)
As part of the [Vuln Scanning
Improvements](https://linear.app/sourcegraph/project/[p0]-vulnerability-scanning-improvements-75299c4312dd/issues)
project, I've been working on tooling to automate the security approval
step of the release process.

This PR integrates these improvements into the release pipeline:

* Internal releases will run a vulnerability scan
* Promote-to-public releases will check for security approval

If a public release does not have security approval, it will block the
promotion process. The step happens at the start of the pipeline so
should be a fast-fail. You can also check for release approval before
running promotion by running `@secbot cve approve-release <version>` in
the #secbot-commands channel. In an ideal world we (security) will have
already gone through and approved ahead of release.

I've tested this PR as much as I can without running an actual release!
We have a 5.5.x release tomorrow so it'll be a good test. If it does
cause problems that can't be easily solved, it can always be temporarily
disabled.

I've tagged this PR to be backported to `5.5.x`.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Pre-merge checklist

- [x] Revert commit that disables release promotion

## Test plan

Manual testing of the release process:
- [x] [Successful test
run](https://buildkite.com/sourcegraph/sourcegraph/builds/283774#0190dfd6-fa70-4cea-9711-f5b8493c7714)
that shows the security scan being triggered
- [x] [Promote to public test
run](https://buildkite.com/sourcegraph/sourcegraph/builds/283826) that
shows the security approval approving a release
- [x] [Promote to public test
run](https://buildkite.com/sourcegraph/sourcegraph/builds/283817#0190e0ec-0641-4451-b7c7-171e664a3127)
that shows the security approval rejecting a release with un-accepted
CVEs

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-24 09:19:49 +01:00
Stefan Hengl
d3528061cd
chore(worker): move llm token counter to worker (#64008)
This moves the LLM token counter from `frontend` to the `worker`.

Test plan:
new unit test
2024-07-24 10:03:33 +02:00
Stefan Hengl
40a436d159
fix(search_jobs): flickering placeholder component (#64009)
We have to use `debouncedSearchTerm` to give the paginated fetcher some
time to fetch the new results.

## Test plan:
visual inspection
2024-07-24 10:02:08 +02:00
Varun Gandhi
1b0e004d03
chore(codeintel): Rename uploads/../Store -> codegraph/../DataStore (#64001)
Also consolidates mocks to avoid wasting time generating
and compiling them repeatedly, and reducing pollution of
Find Usages results in the editor (yes, I know these can be
filtered out, but it's silly to have multiple copies).
2024-07-24 08:24:20 +01:00
Christoph Hegemann
eefcc7ea14
codeintel: fetches diffs from gitserver in batches (#64025)
Closes
https://linear.app/sourcegraph/issue/GRAPH-769/fetch-diffs-in-batches

## Test plan
Covered by existing tests (noticeable because tests need updates as we
now use the path out of the returned diff)
2024-07-24 06:12:47 +00:00
Christoph Hegemann
46e589d6c8
codeintel: runs occurrence and symbol search in parallel (#64023)
Closes
https://linear.app/sourcegraph/issue/GRAPH-767/search-based-run-occurrence-search-and-symbol-search-in-parallel

## Test plan

Covered by existing tests and checking the trace to see executes
overlapping:

![image](https://github.com/user-attachments/assets/75d9644f-cae7-46b9-a1bf-d3cdbb396dc8)
2024-07-24 04:36:49 +00:00
Christoph Hegemann
34e40c372c
codeintel: GitTreeTranslator rewrite (#63938)
Closes
https://linear.app/sourcegraph/issue/GRAPH-742/simplify-gittreetranslator-implementation

- use unified diff format and 0 context lines to allow translation by
just using hunk headers
- only request hunks per file once, and sync follow-up requests for the
same file
- don't bother LRU caching the full hunk contents, just store 4 int32's
per hunk
- replace linear search through sorted hunks with binary search

Current PR keeps the old PR and just proxies to the new implementation.
Once this PR is reviewed and merged I'll remove the old API and update
all callsites.

## Test plan
New/existing tests
2024-07-24 04:13:36 +02:00
Quinn Slack
dd29976250
track usage stats for saved searches in UTC day increments (#63904)
This makes it easier to chart this metric on a daily basis. Transmitting
the count in a rolling 24-hour window is harder.

Note that this new usagestats schema for saved searches has not yet been
released in a patch or stable release.


## Test plan

CI
2024-07-23 19:17:40 -06:00
Robert Lin
e0b959b551
feat/enterpriseportal: support DevOnly in list subscriptions (#63837)
We need to ensure prod data does not end up in the dev Enterprise Portal
instance once we start syncing. This change adds support for the DevOnly
option in ListSubscriptions and strictly enforces it there (i.e. dev
subscriptions cannot end up in the prod instance either).

I've tried to minimize the changes elsewhere to reduce the impact of
this change for now.

## Test plan

Tests
2024-07-23 22:20:35 +00:00
Robert Lin
31b271b491
feat/frontend/dotcom: add toggles for various online license checks (#64013)
Adds the following toggles for various dotcom-mode online licensing
capabilities:

- `DOTCOM_ENABLE_ONLINE_LICENSE_CHECKS=false` makes it so that the
license check "pings" always return "you're good to go"
- `DOTCOM_ENABLE_ANOMALOUS_LICENSE_CHECKER=false` disables the Redis +
event_logs thing looking for suspicious pings
- `DOTCOM_ENABLE_UPCOMING_LICENSE_EXPIRATION_CHECKER=false` disables
Slack notifications for upcoming license expirations

All defaults still respect the existing behaviour.
https://github.com/sourcegraph/deploy-sourcegraph-cloud/pull/18712
explicitly sets the toggles for online license checks, per the
discussion in
https://sourcegraph.slack.com/archives/C012NU3PXA9/p1721669308549559

All of the above capabilities are planned to be migrated to Enterprise
Portal:

- https://linear.app/sourcegraph/issue/CORE-182
- https://linear.app/sourcegraph/issue/CORE-227
- https://linear.app/sourcegraph/issue/CORE-183

## Test plan

CI
2024-07-23 14:45:30 -07:00
Robert Lin
d19c1339a9
feat/enterpriseportal: db layer for subscription conditions (#63812)
Implements insert and retrieval of subscription conditions, similar to
#63792

Unlike for licenses, which have a more limited lifecycle (create and
revoke), subscriptions are longer-lived and may be updated frequently.
So the storage layer allows the caller to provide the conditions that
are of interest for recording.

Part of https://linear.app/sourcegraph/issue/CORE-156, but doesn't yet
use it from the API.
Part of https://linear.app/sourcegraph/issue/CORE-100

## Test plan

Integration tests
2024-07-23 19:27:08 +00:00
Robert Lin
cb7cef0348
chore/enterpriseportal: rewrite subscriptions API tests to be table-driven (#63831)
As we start adding more stuff here, we need a bit more flexibility to
add tests without it becoming overwhelming. The current copy-pasta is
quite difficult to read, this standardizes the expected behaviour for
the Update and List tests.

## Test plan

CI
2024-07-23 12:20:33 -07:00
Vova Kulikov
0a6e509af3
Bring back post-sign-up route to the backend router (#64011)
Fixes [inc-313
](https://sourcegraph.slack.com/archives/C07D8ETFAQP/p1721746352871739?thread_ts=1721745191.614829&cid=C07D8ETFAQP)

It should solve problems with the old auth flow in the new Svelte
version. Currently, the go router doesn't know anything about
post-sign-up flow, which is used in the JB Cody extension. Because of
this, it passes it to the Svelte version which doesn't implement this
route on the client (but the react version did have it on the client
which is why it worked before, before we rolled out Svelte version by
default)

## Test plan
- There is no good way to check this properly, but after this PR you
have to see a react (old) version of the App when you go to the
/post-sigh-up router
2024-07-23 12:27:11 -03:00
Jacob Pleiness
37cf4a7b7e
feature(appliance): UI installs Sourcegraph again (#63996)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

The appliance UI creates a `configMap` that triggers our reconciler to
install Sourcegraph.

- Refactored React app to remove "demo" code where possible
- Added `status` functionality to get the status of deployments,
statefulsets, or persistent volume claims.
- Fix small code issue where `FromInt` was deprecated
- Add reconciliation loop for the appliance backing `configMap`


Install:

```shell
❯ k get pods
NAME                                         READY   STATUS    RESTARTS      AGE
blobstore-568d57d477-k5vrh                   1/1     Running   0             15m
codeinsights-db-0                            2/2     Running   0             15m
codeintel-db-0                               2/2     Running   0             15m
gitserver-0                                  1/1     Running   1 (14m ago)   14m
grafana-0                                    1/1     Running   0             15m
indexed-search-0                             2/2     Running   0             15m
pgsql-0                                      2/2     Running   0             15m
precise-code-intel-worker-6fd4d6c8d5-4rjbc   1/1     Running   1 (14m ago)   15m
precise-code-intel-worker-6fd4d6c8d5-6fjdw   1/1     Running   1 (14m ago)   15m
prometheus-6cd94d7485-4cx7n                  1/1     Running   0             15m
redis-cache-f4dc7d6b8-2tp5v                  2/2     Running   0             15m
redis-store-5d6fcc9c84-7sj8v                 2/2     Running   0             15m
repo-updater-9f695b7d5-r28t7                 1/1     Running   5 (14m ago)   15m
searcher-0                                   1/1     Running   0             15m
sourcegraph-frontend-64cc4458cd-4vdwq        1/1     Running   0             15m
sourcegraph-frontend-64cc4458cd-gd7bf        1/1     Running   0             15m
symbols-0                                    1/1     Running   0             13m
syntect-server-6d5d55fb4f-tgbsc              1/1     Running   0             15m
worker-66b4cd79b5-zw844                      1/1     Running   1 (13m ago)   15m

```

## Test plan

Unit tests where applicable and tested locally via UI and local cluster

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-23 11:06:15 -04:00
Bolaji Olajide
067115910c
fix(ci): check command out for error when git fails (#63993)
Closes [#1110](https://github.com/sourcegraph/devx-support/issues/1110)
Closes DINF-96

We don't print the stdErr when a command fails … in particular when git
fails. Therefore we see very little in the panic of what went wrong.

Explanation:
> There's a weird behavior that occurs where an error isn't accessible
in the err variable
// from a *Cmd executing a git command after calling CombinedOutput().
// This occurs due to how Git handles errors and how the exec package in
Go interprets the command's output.
// Git often writes error messages to stderr, but it might still exit
with a status code of 0 (indicating success).
// In this case, CombinedOutput() won't return an error, but the error
message will be in the out variable.

## Test plan

Manual testing

```go
func main() {
	ctx := context.Background()
	cmd := exec.CommandContext(ctx, "git", "rev-parse", "--is-inside-work-tree")
	out, err := handleGitCommandExec(cmd)
	if err != nil {
		// er := errors.Wrap(err, fmt.Sprintf("idsdsd: %s", string(out)))
		panic(err)
	}
	fmt.Println("hello", string(out))
}
```

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-23 09:56:33 -05:00
Varun Gandhi
d93c0fdf90
chore: Document tech debt wrt multiple doc traversals (#64006) 2024-07-23 15:19:20 +02:00
Noah S-C
49b9b10468
chore(bazel): disable stamping on rust_binary targets (#64007)
We don't appear to make use of the stamp values for any rust_binary
targets, so lets not stamp it to save on cache invalidations

## Test plan

```
$ bazel build --stamp --workspace_status_command=./dev/bazel_stamp_vars.sh $(bazel query 'kind("rust_binary", //...)')
...
$ sha256sum bazel-bin/docker-images/syntax-highlighter/scip-ctags bazel-bin/docker-images/syntax-highlighter/crates/scip-syntax/scip-syntax bazel-bin/docker-images/syntax-highlighter/syntect_server
...
$ bazel build $(bazel query 'kind("rust_binary", //...)')
...
$ sha256sum bazel-bin/docker-images/syntax-highlighter/scip-ctags bazel-bin/docker-images/syntax-highlighter/crates/scip-syntax/scip-syntax bazel-bin/docker-images/syntax-highlighter/syntect_server
...
```
observe identical checksums

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-23 12:22:50 +00:00
Petri-Johan Last
777c7a0899
[logging] Only record events if a new user was created (#64004) 2024-07-23 13:48:11 +02:00
Rafał Gajdulewicz
a7f787a772
Implement server-side single-repo context fetching for RFC 969 (#63980)
Implements server-side part of AI-132, exposing a single-repo context
endpoint backed by Zoekt.

Differences from the current Enterprise endpoint (that is left
untouched):

- supports a single repo only
- supports passing a repo name, not Sourcegraph-assigned repo ID
- has a shorter, 5s timeout
- reports partial errors (if we hit issues converting search results to
git results, or if some retrievers time out)

## Test plan

- tested locally with 
```
{
  chatContext(
    query: "squirrel"
    repo: "github.com/sourcegraph/sourcegraph"
    interactionId: "foo"
  ) {
    contextItems {
      score
      retriever
      item {
        ... on FileChunkContext {
          blob {
            path
            repository {
              id
              name
            }
            commit {
              oid
            }
            url
          }
          startLine
          endLine
          chunkContent
        }
      }
    }
    partialErrors
  }
}

```
2024-07-23 13:36:00 +02:00
Varun Gandhi
978abd5020
chore(codeintel): Pass UsageKind instead of raw column names (#64003)
Pass down semantic information down as much as possible,
delaying lossy conversion to table names till the very end.

I will be introducing the `exhaustive` linter in a future PR
(https://golangci-lint.run/usage/linters/#exhaustive)
so that we can get a static error if you don't switch exhaustively.
2024-07-23 12:28:55 +02:00
Varun Gandhi
eeded69538
feat(build): Add exhaustruct linter (codeintel POC) (#63965)
For certain types, we do not want the zero-value initialization for structs.
This means we need to trade off readability vs exhaustive initialization
checking, as the Go syntax `Foo{Bar: bar}` is more readable, but doesn't do
exhaustiveness checking, and `Foo{bar}` does check for exhaustiveness but can be less
readable depending on context.

For now, the check is only introduced for one type, and is meant to be
opt-in so that code authors may choose for stricter checking.
2024-07-23 17:26:01 +08:00
Craig Furman
49a600220d
feat(appliance): deploy otel-agent (#63991)
Relates to
https://linear.app/sourcegraph/issue/REL-81/service-definition-otel-collector
but does not close it.
2024-07-23 09:04:12 +00:00
Craig Furman
6e31f0f4cc
chore(appliance): fix a failing test (#64002)
Semantic merge conflict in a test fixture, not caught by actual merge
conflict though.
2024-07-23 08:57:24 +00:00
Craig Furman
daae9adfb6
chore(appliance): split otel collector and agent (#63989)
Relates to

https://linear.app/sourcegraph/issue/REL-81/service-definition-otel-collector
but does not close it.

Some of the StandardConfig features (notably PodTemplateConfig) assume
that there is only one pod template "thing" per service. The otel
service contains an agent daemonset and a collector deployment, which
have quite different characteristics. We're less likely to paint
ourselves into a corner if we split these services at the config level.
2024-07-23 09:38:40 +01:00
Varun Gandhi
548cb609f3
chore(codeintel): Move mock generation near interface package (#64000)
This patch moves the mocks for `codenav/../lsifstore` package to a
separate package `lsifstore/mocks` instead of it living in `codenav`.
The problem is that if you update the `LsifStore` interface, then you
get an error when trying to regenerate mocks, as regeneration happens
in the `codenav` package, and that package's old mocks no longer
satisfy the new interface (so there is an error when looking at other test
files). Moving the codegen to a separate package avoids this problem.
2024-07-23 09:24:53 +01:00
Stefan Hengl
b2014e6abb
chore(search_jobs): improve description on main page (#63992)
The current description doesn't do a good job of explaining why Search
Jobs is useful and how to create a job.

## Test plan:
visual inspection

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-07-23 09:49:24 +02:00
Keegan Carruthers-Smith
48d61c44d3
cody: correct link to emacs-cody (#63974)
Test Plan: clicked link in editor to see if correct

Fixes https://github.com/sourcegraph/emacs-cody/issues/33
2024-07-23 09:40:49 +02:00
Stefan Hengl
8f7055249b
chore(worker): move event_logs janitor routines to worker (#63981)
This moves the janitor jobs for event logs from `frontend` to `worker`.

Next up: move the other recurring jobs as well.

## Test plan
- new unit tests
- manual testing: the worker dashboard showed the job is running
2024-07-23 09:40:22 +02:00
Varun Gandhi
2f09a80b6d
chore(codeintel): Move RequestState construction to separate func (#63998)
Separating out the logic into a different function so it can be reused
later for precise usagesForSymbol.
2024-07-23 07:09:27 +00:00
Varun Gandhi
dc693b504f
chore(codeintel): Simplify code using upload filtering (#63997)
A bunch of logic was constructing "visibleUpload" values but
it just needed to pass around CompletedUpload. Simplify that.
2024-07-23 14:50:01 +08:00
Varun Gandhi
08ec7cad5b
chore(codeintel): Derive TargetPathWithoutRoot dynamically (#63986)
We only need to two out of three for representing a document in an
upload:

1. Upload root
2. RepoRootRelPath
3. UploadRootRelPath

For simplicity, drop the 3rd one, deriving it dynamically
from the other two as needed.
2024-07-23 06:57:15 +02:00
Michael Bahr
cc1f52f259
feat: order search filters alphabetically (#63976)
Closes SRCH-771

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-22 16:33:44 -07:00
Warren Gifford
0e391a964a
Feature(appliance): db connection pinger and validator (#63884)
Introduce a pinger for the appliance to poll the various Sourcegraph dbs
and ensure connection is possible given the current connection envvar
configuration.

## Test plan

Unit Tests

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-22 22:34:42 +00:00
Quinn Slack
1ce261c4bf
fix incorrect URL (/new) on saved search and prompt library pages (#63995)
Also update page title.

Fixes
https://linear.app/sourcegraph/issue/CODY-3026/when-the-new-fast-ui-is-enabled-the-new-button-on-saved-searches-and

## Test plan

CI
2024-07-22 16:27:02 -06:00
Anish Lakhwara
0abef7b43d
chore(appliance): make a function less misleading (#63994)
isNamespaced was implemented the opposite way to its name, returning
true when a resource was _not_ namespaced. We could have renamed it to
isNotNamespaced, but then most callsites would look like a double
negative. So this commit inverts the implementation to match the name,
and also its callers.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

Forked from https://github.com/sourcegraph/sourcegraph/pull/63972 to
clean up the branch

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-22 13:42:41 -07:00
Anish Lakhwara
a61f353e0e
feat(appliance): Adopt Frontend Service + Ingress (#63893)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Resolving section 1
[REL-213](https://linear.app/sourcegraph/issue/REL-218/ingressservice-consistency-for-helm-deployment):
Setting controllerOwner references to k8s objects that will exist before
appliance is installed.
Part 2 (serializing helm values into an annotation and using that as
input) will happen in a subsequent PR

We need to adopt Frontend's `Service` and `Ingress` for Appliance to
manage.

~~This is still a work in progress PR.~~

Currently handles and adopts frontend's Service (golden test included)
Yet to adopt frontend's Service. 

## Test plan
Golden test included
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
- feat(appliance): Appliance adopts Frontend's `Ingress` + `Service`

---------

Co-authored-by: Craig Furman <craig.furman@sourcegraph.com>
2024-07-22 19:37:12 +00:00
Ara
1ca6385b1b
Special oauth containers (#63880)
[See a description in Linear 

](https://linear.app/sourcegraph/issue/CODY-2845/supporting-special-azure-openai-configurations-for-enterprize#comment-6938baa0)

## Test plan
Tested with local builds and see linear for more. 

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-22 17:31:03 +02:00
Petri-Johan Last
874c9f6bd3
refactor(github): Have a dedicated PublicRepository type (#63607) 2024-07-22 17:21:30 +02:00
Will Dollman
b7242d280f
Publish images for all commits on release branches (#63985)
In order to run nightly vulnerability scans of Sourcegraph releases, we
need to publish a new set of images whenever the release branch is
pushed to.

Previously, this was implemented in
https://github.com/sourcegraph/sourcegraph/pull/63379 but with RFC 795
the release branch format changed from 5.5.1234 to 5.5.x.

This PR updates the regex to catch this new format.

The end result of this is that whenever Buildkite runs on a branch
matching `\d.\d.x`, it will push images to the
`us.gcr.io/sourcegraph-dev/gitserver` registry with the tag
`$branch-insiders`.

I've also tagged this PR for backport as we want it on the current patch
release branch 5.5.x :)

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

- Test buildkite run on branch `will-0.0.x` (with modified regex to
match that branch)
https://buildkite.com/sourcegraph/sourcegraph/builds/283608

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-22 16:12:56 +01:00
Varun Gandhi
a6b6844678
chore: Rename Index -> AutoIndexJob (#63955)
Also renames a bunch of related types such as
- config.IndexJob -> config.AutoIndexJobSpec
- IndexLoader -> AutoIndexJobLoader

and so on.
2024-07-22 22:18:40 +08:00
Vincent
5fdaa583e0
GraphQL: improve query cost violation message (#63921)
It's a bit unclear for users what the error message is for. This PR
improves the error message by extending the GraphQL error message with
additional context.

Linear issue:
https://linear.app/sourcegraph/issue/SEC-1792/add-error-message-specifying-which-cost-setting-was-exceeded-in.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
CI tests
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-22 15:09:04 +01:00
Christoph Hegemann
3ef0be193d
Adds unit tests for syntactic usages (#63900)
Closes
https://linear.app/sourcegraph/issue/GRAPH-735/test-syntactic-usages

Uses the new MappedIndex abstraction from #63781 to implement some
proper unit tests for `syntacticUsagesImpl`.

## Test plan

PR adds a bunch of tests
2024-07-22 13:24:30 +00:00
Varun Gandhi
12ba6ca10e
chore(codeintel): Rename local variables for clarity (#63983)
There are many occurrences flying around, so add some prefix to identify
the fact that some values are used for lookups (whereas other values
are the results of the lookup -- these are not specially marked).
2024-07-22 13:16:34 +00:00
Varun Gandhi
a5dad3b3a2
chore: Rename URI -> DocumentPath (#63979)
If you look at the code for `bulkMonikerResultsQuery` and
`minimalBulkMonikerResultsQuery`, you'll see that the last
returned value is the `document_path`. The value returned
was directly used an `UploadRootRelPath` elsewhere. So it
makes sense to rename the field from URI to `DocumentPath`.

## Test plan

Covered by existing tests
2024-07-22 15:11:49 +02:00
Petri-Johan Last
cd65951961
[fix] Only trigger externalAcctSignup event when a new user is created or external account is saved (#63843) 2024-07-22 13:42:29 +02:00
Craig Furman
e81c39a834
feat(appliance): redeploy various services when pg/redis config changes (#63954)
Builds on
https://github.com/sourcegraph/sourcegraph/pull/63845, and closes
https://linear.app/sourcegraph/issue/REL-14/ensure-pods-roll-when-referenced-secret-changes.

When one of the 3 DB configs changes, an annotation "checksum/auth" on
frontend's deployment's spec.template.metadata should change on next
reconcile. This will cause pods to roll, picking up the new secret
values. It should also cause the top-level annotation configHash to
change, which indicates to the appliance that the kubernetes resource
should be updated.

A similar mechanism is implemented for "checksum/redis", on every
service that uses redis (obtained by grepping the helm chart for the
same annotation).
2024-07-22 09:44:12 +01:00
Varun Gandhi
5a52cbc106
chore: Mark flaky test as manual (#63968)
See [Slack thread](https://sourcegraph.slack.com/archives/C05EMJM2SLR/p17214841097005390)
for the many different failure modes this test is running into when
running with

```
bazel test //internal/grpc/retry:retry_test --runs_per_test=100 --jobs=1
```
2024-07-22 09:29:38 +02:00
Varun Gandhi
6bbcede760
fix: Synchronize access to reads of fields in retry test (#63967)
The reads for `s.streamFailureFunc` and `s.streamError` fields must be
mutex protected since another method may perform writes to those
fields at the same time, and both reads and writes must use the same mutex.

## Test plan

I ran `bazel test //internal/grpc/retry:retry_test --runs_per_test=100`
and no longer see a data race failure, but I see other errors, see
[Slack thread](https://sourcegraph.slack.com/archives/C05EMJM2SLR/p1721484109700539).
2024-07-22 09:29:09 +02:00
Varun Gandhi
fb51358cce
chore: Remove unused TTL in object.Storage config (#63947)
In this PR (https://github.com/sourcegraph/sourcegraph/pull/45042), it
is noted that:

> Removed lifecycle configuration from uploadstore, instead relying just
> on our own builtin background worker to expire objects.

As a result, the `TTL` field on the GCS Client was not used anywhere. So
this patch removes the TTL field.
2024-07-22 02:58:57 +00:00
Quinn Slack
1fe876e89c
finish removing chromatic (#63966)
We removed Chromatic in
https://github.com/sourcegraph/sourcegraph/pull/62228, but there were
still some remnants.

## Test plan

CI
2024-07-21 18:37:02 -07:00
Varun Gandhi
9145768648
chore: Rename uploadstore packages for clarity (#63931)
- The `internal/uploadstore` package is renamed to `object` indicating
   that it is meant to provide a generic object storage wrapper.
- The `search/exhaustive/uploadstore` package is used in very few places
  so I've merged into the `internal/search` package similar to
  `internal/embeddings`.

There are a few reasons to do the renaming.

1. The word `upload` in a more general context is ambiguous (just in
    `internal/`) - in the codeintel context, it means "SCIP index" but it
    can also be interpreted generically ("upload of _some_ data").
2. Better readability - `object.Storage` is much shorter than
    `uploadstore.Store`. Additionally, we use the term `Store` A LOT
    in the codebase, and usually, these refer to wrappers over some
    tables in some DB.

    Making things worse, some of our code also has:

    ```
    uploadsstore
"github.com/sourcegraph/sourcegraph/internal/codeintel/uploads/internal/store"
    ```

And code which says `uploadsstore.Store` (notice the extra `s` 😢), which
is actually a wrapper over some key DB tables like `lsif_uploads`.
2024-07-22 08:57:56 +08:00
Quinn Slack
30c0184f25
various OrgArea fixes (#63962)
- Make it a React function component (not class componnt)
- Remove prop drilling for isSourcegraphDotCom to remove a bunch of code
- fix issue in Back button after clicking to an org from the site admin
orgs page. Repro: 1. Go to /site-admin/organizations. 2. Click on an
org. 3. Click the browser's back button. This was already being done for
the user routes.

## Test plan

Repro described above
2024-07-20 20:45:32 -07:00
Quinn Slack
341bfe749f
allow site admins to list org members & view user/org settings on dotcom (#63963)
Followup from https://github.com/sourcegraph/sourcegraph/pull/63941.

I forgot to make it so site admins could list org members in that PR.

As for the new ability for site admins to see user and org settings:
Site admins could already add themselves to orgs as members and see
settings that way. I considered still keeping it stricter, but it is
valuable for site admins to be able to view settings to help users
troubleshoot.


## Test plan

In dotcom mode, as a site admin, view a user or org (that the site admin
is not a member of). Confirm that the settings can be viewed.
2024-07-19 21:01:49 -07:00
Vova Kulikov
492ddef497
Svelte: Fix Safari 17.3 groupBy usage (#63964)
Currently, svelte build of Sourcegraph is broken on s2 and dotcom for
users who use Safari 17.3 and lower
The problem is that we use the `Object.groupBy` method, which isn't
supported in "old" Safari versions like 17.3 and lower. See caniuse
documentation about this here https://caniuse.com/?search=groupBy (in
the old Safari version this method is actually named `groupToMap`

## Test plan
- Check basic functionality Search flow in Safari (especially in Safari
17.3)

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-19 18:43:29 -07:00
Quinn Slack
b5ac21bda5
upgrade vitest to latest (#63951)
## Test plan

CI
2024-07-19 16:19:12 -07:00
Camden Cheek
781aebb13a
Svelte rollout: add toggles for svelte-enabled pages (#63960)
This is the last bit of work before flipping the switch on dotcom.
Implemented based on the behavior @taiyab and I aligned on this morning.
Can definitely still use a little sparkle, but I'll let others follow up
on that.

It adds a toggle button to all pages that we have a svelte version of.
The toggle is off when you're in the react webapp and on when you're in
the svelte webapp. It also updates the copy of the popover to be more
appropriate for the dotcom crowd.
2024-07-19 16:56:08 -06:00
Quinn Slack
d33b87cb64
support getting other orgs on dotcom from the GraphQL API (#63941)
Previously, the GraphQL API on dotcom only let org members query for an
org (through `organization(name: ...)` or otherwise). This made sense as
a strict security safeguard in a world where an org had only private
resources, not public resources.

However, with search contexts, saved searches, and now the new prompt
library, we want orgs on dotcom to be able to create things that (if we
or they intentionally make them public) all users can see, and can see
the association with the org owner. That requires all users to be able
to query for the org and see its name.

We continue to enforce the secrecy of much org data: members (only org
members can list the other members of the org), settings (only org
members can view this).

**But the name, displayName, and existence of an org will now be
considered public.**

## Test plan

In dotcom mode, view an organization.
2024-07-19 15:49:09 -07:00
Quinn Slack
f63371392a
fix saved searches and prompts list page for anon users (#63961)
Anonymous visitors to Sourcegraph.com were unable to list all public
saved searches (at https://sourcegraph.com/saved-searches) and prompts
(at https://sourcegraph.com/prompts) for 2 reasons:

1. The namespace selector (filter) was broken for anonymous users and
returned an error. Fixed this by just handling this case.
2. The GraphQL resolvers for `savedSearches` and `prompts` prevented
anonymous users from listing items because there was no affiliated user
and thus the anonymous user was essentially trying to list all. Fixed
this by adding a new and well-tested code path for listing only public
saved searches or prompts.

## Test plan

In dotcom mode, visit those 2 pages (`/saved-searches` and `/prompts`).
2024-07-19 15:43:04 -07:00
Robert Lin
df228a7580
feat/enterpriseportal: db layer for cody gateway access (#63737)
Implements Cody Gateway access in Enterprise Portal DB, such that it
replicates the behaviour it has today, retrieving:

- Quota overrides
- Subscription display name
- Active license info
- Non-revoked, non-expired license keys as hashes
- Revocation + non-expiry replaces the existing mechanism of flagging
licenses as `access_token_enabled`. Since we ended up doing zero-config
for Cody Gateway, the only license hashes that are valid for Cody
Gateway are non-expired licenses - once your license expires you should
be switching to a new license key anyway.

It's fairly similar to the `dotcomdb` shim we built before, but for our
new tables. See https://github.com/sourcegraph/sourcegraph/pull/63792
for the licenses tables.

None of this is going live yet.

Part of https://linear.app/sourcegraph/issue/CORE-100
Part of https://linear.app/sourcegraph/issue/CORE-160

## Test plan

DB integration tests

`sg run enterprise-portal` does the migrations without a hitch
2024-07-19 14:06:27 -07:00
Geoffrey Gilmore
7a16ccf912
fix/database/sub_repo_perms: don't mark TestSubRepoPermsStore_GetByUserWithIPs as Parallel (#63958)
See https://sourcegraph.slack.com/archives/C03K05FCRFH/p1721387628038419

We'll see if this fixes the race condition?

I believe multiple tests are setting the mock configuration object via conf.mock - so hopefully removing the t.Parallel() call fixes the issue.

## Test plan

CI passes 

## Changelog

- A race condition in the sub_repo_permissions database store test suite has been fixed.
2024-07-19 13:51:48 -07:00
Robert Lin
30d50b72a2
feat/sg: add 'sg sams client create' (#63885)
Adds an equivalent to the curl command we currently share, but in `sg`.
If we add a better API around this later it's just an in-place
replacement.

Similar to https://github.com/sourcegraph/sourcegraph/pull/63883 this
"just works" with zero configuration against SAMS-dev.

Part https://linear.app/sourcegraph/issue/CORE-220, a spike into
polishing some local-dev DX for SAMS.

## Test plan

```
sg sams client create -redirect-uris='https://sourcegraph.test:3443/.auth/callback' robert-testing
```

if you hit an error loading the secret, e.g. targeting the prod
instance, you get a suggestion to get Entitle access:

```
sg sams client create -redirect-uris='https://sourcegraph.test:3443/.auth/callback' -sams='https://accounts.sourcegraph.com' robert-testing
⚠️ Running sg with a dev build, following flags have different default value unless explictly set: skip-auto-update, disable-analytics
👉 Failed to get secret - do you have Entitle access to the "sourcegraph-accounts-prod-csvc" project? See https://sourcegraph.notion.site/Sourcegraph-Accounts-infrastructure-operations-b90a571da30443a8b1e7c31ade3594fb
 google(sourcegraph-accounts-prod-csvc): failed to get secret "MANAGEMENT_SECRET": rpc error: code = PermissionDenied desc = Permission 'secretmanager.versions.access' denied for resource 'projects/sourcegraph-accounts-prod-csvc/secrets/MANAGEMENT_SECRET/versions/latest' (or it may not exist).
```
## Changelog

- `sg sams client create` can now be used to create IdP clients for
SAMS.

---------

Co-authored-by: Erik Seliger <erikseliger@me.com>
2024-07-19 13:41:28 -07:00
Robert Lin
f53e211804
feat/sg: prototype 'sg start sourcegraph-accounts' (#63894)
Prototype what it might be like to have `sg` run `sourcegraph-accounts`.
I think this would be a huge improvement over the multi-step,
many-things-to-install process that currently exists for SAMS.

There are a couple of quirks, but I think I'll leave this here for now,
as this is part https://linear.app/sourcegraph/issue/CORE-220, a
timeboxed spike into polishing some local-dev DX for SAMS.

Also see https://github.com/sourcegraph/sourcegraph-accounts/pull/262

## Test plan

```
sg start sourcegraph-accounts
```

Go to 127.0.0.1:9991 and try to log in
2024-07-19 13:30:08 -07:00
Erik Seliger
924c5d263c
repoupdater: Make batches init jobs dependent on batches.IsEnabled (#63939)
One less dotcom specific check, and makes it so we truly disable the
batches background jobs as well.

Test plan: Still runs the batches jobs locally.
2024-07-19 21:53:37 +02:00
Erik Seliger
3218d2ddc9
Remove old reference to env var that no longer exists (#63656)
This doesn't apply anymore. Cleaning up a comment.

Test plan: CI.
2024-07-19 21:53:15 +02:00
Erik Seliger
c4abb510b1
schema: Remove unused extension schema file (#63657)
The schema file was removed long ago, this removes the Go code for it as
well, as there are no more references to it.

Test plan:
Go compiler doesn't complain about missing symbols.
2024-07-19 21:42:49 +02:00
Anish Lakhwara
c47e587dc5
fix(release): misc fixes to private promote images script (#63957)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Misc fixes to the `promote_images.sh` script that are known. Notably,
create the annotations directory if it doesn't exist

## Test plan
Tested manually
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-19 19:25:35 +00:00
Robert Lin
51bfacf851
feat/sg: allow sg commands to default to local-dev SAMS-dev credentials (#63883)
As it says on the tin - various commands related to SAMS can now target
dev services integrated against SAMS-dev directly. See test plan for
examples.

I've also refactored the `sg sams introspect-token` etc commands in
preparation for introducing more `sg sams` commands - the existing
commands are now collapsed into `sg sams token introspect` and `sg sams
token introspect -p`

Part https://linear.app/sourcegraph/issue/CORE-220, a spike into
polishing some local-dev DX for SAMS.

I also upgrade the glamour library because I noticed the JSON
pretty-printing was no longer colored - the upgrade fixed that

## Test plan

All the below now work with no additional effort:

```sh
# get token details and print a temporary token
sg sams token introspect -p
# list enterprise-portal-dev data
sg enterprise subscription list -member.cody-analytics-viewer 'robert@sourcegraph.com'
```

You can use it against locally running services that connect to SAMS-dev
as well, for example the below also works with no additional
flags/envvars:

```sh
sg start dotcom # includes enterprise-portal
sg enterprise subscription list -enterprise-portal-server=http://localhost:6081
```

## Changelog

- `sg` commands requiring SAMS client credentials now load shared
SAMS-dev client credentials by default.
2024-07-19 11:25:26 -07:00
Robert Lin
d73e4639b0
fix/frontend/httpapi: improve request reader (#63923) 2024-07-19 19:10:41 +01:00
Camden Cheek
033cb9d901
Search: add regex support to repo:has.meta() (#63891)
This adds support to searching for repo metadata with a regex pattern.

Background: repo metadata is a useful feature for shoehorning
business-specific information into the search query language. It allows
tagging repos with arbitrary metadata (think ownership info, quality
info, 3rd-party system IDs, etc.). This ends up being a useful escape
hatch to shim in functionality that is not natively supported in
Sourcegraph.

However it's currently limited to searching with an exact key/value
pair. We've had a few requests to extend this to allow searching by
pattern because it enables ingesting semi-structured data and making it
searchable.

This adds the ability to use a `/.../`-delimited regex pattern to match
against both keys and values. For example,
`repo:has.meta(team:/^my\/org/)`
2024-07-19 11:53:24 -06:00
Petri-Johan Last
2994636bbc
[update] Remove sleep in goroutine for webhook handlers (#63940)
Since permission sync jobs are database backed, we no longer need to
sleep in the webhook handler goroutines, since the permission sync jobs
have a sleep time themselves.

## Test plan

Tests still pass, no real functional changes.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-19 18:45:16 +02:00
Chris Smith
0212a47690
Fixes re: Cody Pro x Sourcegraph-supplied models (#63892)
This PR fixes several issues related to CodyPro/Sourcegraph.com relying
on Sourcegraph-supplied models.

When Sourcegraph.com is _exclusively_ using the modelconfig systems we
can delete a lot of this code, and all of the hard-coded lists of LLM
models. However, in order to support a smoother transition, we need to
support Sourcegraph.com _not_ using Sourcegraph-supplied models, as well
as updating the site configuration so that it does.

This PR makes the following fixes:

- For forwards compatibility, Sourcegraph.com will now support model
references using the "mref format" (a:🅱️:c). Whereas previously it
_only_ would support the legacy format (a/b). This will allow us to
update Cody clients to use mrefs natively.

- Add virtualized models to the hard-coded list of Cody Pro chat models.
If Sourcegraph.com is using Sourcegraph-supplied LLM models, then it
will use ModelID "claude-3-sonnet" to refer to the LLM model with
ModelName "claude-3-sonnet-20240229". We now accept the virtualized
model name inside of `func isAllowedCodyProChatModel(...)`, as well as
"devirtualize" the model name inside of `func
resolveRequestedModel(..)`.

- Use the Cody Pro user's access token for calls to Cody Gateway. This
is a serious bug that is live today. (⚠️😬) For Sourcegraph.com, when we
call Cody Gateway we do _not_ want to authenticate the request using the
Sourcegraph license key. And instead use the end user's credentials.
However, inside of the Cody Gateway completions client, we were not
actually using that access token.

See:
dbf420bb8c/internal/completions/types/types.go (L61-L75)

> I'll try to add a unit test to ensure this behavior before submitting,
but wanted to get the PR sent out for review ASAP.

## Test plan

Added, updated unit tests. Tested manually.

## Changelog

NA
2024-07-19 09:36:26 -07:00
Michael Bahr
36eb1b991e
chore(svelte): fix test by removing duplicate aria-label (#63942)
The test that I enable in this PR has been skipped for a while, and has
broken again with https://github.com/sourcegraph/sourcegraph/pull/63463,
where we added another aria-label. This additional label lead to
playwright rejecting the test, because it found two elements for one
query.

This PR removes that label, since we already have a similar one at the
button one level up. See screenshot below.

<img width="1001" alt="Screenshot 2024-07-19 at 11 22 24"
src="https://github.com/user-attachments/assets/9b36e157-7c53-42f2-b309-e18c45e631a3">

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-19 08:35:26 -06:00
Rafał Gajdulewicz
8bd9c5d1a4
Add counter for traced requests to Fireworks (#63953)
Adds a otel counter to measure how many traced requests we sent to
Fireworks from Cody Gateway -
[context](https://sourcegraph.slack.com/archives/C0729T2PBV2/p1721385268801079?thread_ts=1721029684.522409&cid=C0729T2PBV2)

## Test plan

- tested locally by sending a request without the `X-Fireworks-Genie`
header, with the header but with value != `true` and with the header and
value `true` and observing `fireworks-traced-requests` Prometheus metric
2024-07-19 14:32:19 +00:00
Taras Yemets
26df35a69f
fix(cody): use client-provided timeout for completions requests (#63875)
Closes
[CODY-2775](https://linear.app/sourcegraph/issue/CODY-2775/%5Bautocomplete-latency%5D-apply-the-same-timeout-on-the-cody-gateway-side)



Enables client control over the request processing timeout on the server
(both Sourcegraph backend and Cody Gateway). The context timeout is set
to the value provided in the `X-Timeout-Ms` header of the client
request. If the header is not provided, the default context timeout is
used (1 minute on both Sourcegraph backend and Cody Gateway).

Previously, we only had a default timeout on the Sourcegraph backend
side (8 minutes).

Corresponding client change:
- https://github.com/sourcegraph/cody/pull/4921

<!-- 💡 To write a useful PR description, make sure that your description
covers:
- WHAT this PR is changing:
    - How was it PREVIOUSLY.
    - How it will be from NOW on.
- WHY this PR is needed.
- CONTEXT, i.e. to which initiative, project or RFC it belongs.

The structure of the description doesn't matter as much as covering
these points, so use
your best judgement based on your context.
Learn how to write good pull request description:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e?pvs=4
-->


## Test plan
- Manually tested and confirmed that if the request contains the
`X-Timeout-Ms` header, its value is used. If not, the default maximum
request duration is applied.
- CI
- 
<!-- All pull requests REQUIRE a test plan:
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->


## Changelog
- Use the provided timeout from request parameters if available;
otherwise use the default maximum request duration (8 minutes)

<!--
1. Ensure your pull request title is formatted as: $type($domain): $what
2. Add bullet list items for each additional detail you want to cover
(see example below)
3. You can edit this after the pull request was merged, as long as
release shipping it hasn't been promoted to the public.
4. For more information, please see this how-to
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c?

Audience: TS/CSE > Customers > Teammates (in that order).

Cheat sheet: $type = chore|fix|feat $domain:
source|search|ci|release|plg|cody|local|...
-->

<!--
Example:

Title: fix(search): parse quotes with the appropriate context
Changelog section:

## Changelog

- When a quote is used with regexp pattern type, then ...
- Refactored underlying code.
-->
2024-07-19 14:17:02 +00:00
Craig Furman
619fc57074
feat(appliance): roll frontend deployment when pgsql secret changes (#63845)
This approach is a bit of a departure from how our helm chart works.
That hashes hashes values blocks to determine these annotations. The
issue is, that these values blocks often contain references to secrets,
and therefore don't change when the _content_ of the secret changes.

This PR takes a more general approach of looking for that secret, which
must always eventually exist - whether admin-provisioned or provisioned
by the pgsql service definition - and hashes that.
2024-07-19 15:00:22 +01:00
Quinn Slack
4918fa7eef
show org name not displayName in most places (#63907)
Previously, organizations would be displayed using their `displayName`,
which was inconsistent and non-canonical. The `displayName` is also
longer, so it's not suited to display in select menus and other similar
places.

For example, when viewing the user menu or creating a batch change or
saved search, the dropdown will now show `sourcegraph` instead of
`Sourcegraph` (where the latter is the display name).


![image](https://github.com/user-attachments/assets/79bce594-49c9-4603-9757-2e6785b26be9)


## Test plan

Go to create a batch change or saved search and confirm that org names
not displayNames are shown.

## Changelog

- The user menu and other filter menus now show the names of
organizations, not their "display names", to avoid ambiguity. For
example, these menus will now show `abc-corp` not `ABC Corp` (if the
latter was the `abc-corp`'s display name).
2024-07-19 12:30:09 +00:00
Quinn Slack
238831741e
use the viewerSettings GraphQL API instead of the 5y+-deprecated viewerConfiguration API (#63949)
This API is deprecated (see
https://github.com/sourcegraph/sourcegraph/pull/63935). The browser
extension is still using it, and we need this PR to remove its usage,
and then we need to publish it. Then we can pick up
https://github.com/sourcegraph/sourcegraph/pull/63935 again.

## Test plan

Confirm that the browser extension uses the new GraphQL query (in the
background page network devtools tab).
2024-07-19 11:42:25 +00:00
Erik Seliger
175667db7c
gitserver: Add OctopusMergeBase RPC method (#63842)
This method can be used to find a common ancestor for many commit SHAs,
to be used by code intel for finding visible uploads.

Closes SRC-485

Test plan: Added unit tests for the several layers (client, grpc,
gitcli).
2024-07-19 13:25:09 +02:00
Erik Seliger
36d785dc4a
dotcom: Remove dotcom on-by-default Cloudflare trust mode (#63658)
https://github.com/sourcegraph/deploy-sourcegraph-cloud/pull/18673
configures this env var explicitly. This feels cleaner than having
yet-another-dependence-on-this-env-var.

Test plan: Check in after rollout.
2024-07-19 11:38:46 +01:00
Quinn Slack
702b346986
explicitly check viewer access to settings in GraphQL API (#63945)
Previously, a user's or org's settings were protected from unauthorized
access in the GraphQL API by access checks far from the actual
`SettingCascade` and `LatestSettings` implementations in most cases.
This did not present a security issue because on Sourcegraph.com we
prevented users from getting a reference to an org they aren't in, and
user settings had the right manual access checks.

But the access checks are too far away from the actual resolver methods
(so it'd be easy to make a mistake) and were not consistently
implemented. **Now, all checks for view-settings-of-subject access go
through the same function, `settingsSubjectForNodeAndCheckAccess`.**

One substantive security change is that now site admins may NOT view the
settings of an org they are not a member of. This is in line with site
admins on dotcom not being able to see user settings. This is important
because settings might contain secrets in the future (e.g., OpenCtx
provider config). Site admins may still add themselves to the org and
then view the settings, but that creates more of an audit trail and and
we may lock down that as well.



## Test plan

Unit tests, also browse around the UI and ensure there are no code paths
where our assertion triggers.
2024-07-19 03:26:03 -07:00
Quinn Slack
0e958d19d6
misc improvements to graphqlbackend (#63943)
- skip graphqlbackend tests that use the DB when using `go test -short`
- fix race condition in (settingsResolver).Author
- fix OrgMembers.GetByOrgIDAndUserID mocks: The actual function returns
a non-nil error (`database.ErrOrgMemberNotFound` type) when the user is
not an org member. Our mocks should do the same for correctness.

## Test plan

CI
2024-07-19 09:44:14 +00:00
Erik Seliger
9491958e78
gitserver: Add option to allow setting custom context line count (#63840)
This PR adds support for two new arguments in the gitserver API:
InterHunkContext and ContextLines.
See the inline docstring for the two, but basically this allows to
request diffs with a custom amount of context lines and hunk merging.

The defaults should be unchanged at `3` for both, according to
https://sourcegraph.com/github.com/git/git/-/blob/diff.c?L60.

Closes SRC-467

Test plan:

Added unit tests.
2024-07-19 10:50:49 +02:00
Quinn Slack
2451aab9f8
saved searches & prompt library fixes (#63930)
- Add spacing at bottom of page
- Fix viewerCanAdminister check to return `false` not an error when the
user is not an administrator of a saved search or prompt
- Improve display of prompt description


## Test plan

In dotcom mode, try loading a prompt or saved search in incognito mode.
2024-07-19 08:41:47 +00:00
Quinn Slack
3c8b8e9e25
show "Copied" indicator when copying an access token (#63936)
For some reason, the indication that the text was copied was removed for
secrets. The indication does not show the secret value itself, so I
don't see why that change was made. It is helpful to the user to give
them feedback that the secret was in fact copied.


## Test plan

Click the copy button after creating an access token
2024-07-19 01:21:07 -07:00
Quinn Slack
6f0c1358e9
remove "organizations aren't supported" page on dotcom (#63932)
We want to support orgs on dotcom for grouping prompts in the Prompt
Library. Note that creating orgs was never actually disabled in the API,
so this was ineffectual anyway.


## Test plan

View the user settings area sidebar in dotcom mode and ensure the new
org button is shown.
2024-07-19 01:20:56 -07:00
Quinn Slack
6616eb1635
prevent orgs from being named "global" on dotcom (#63933)
This could be confused with an official global namespace.


## Test plan

CI
2024-07-19 01:20:49 -07:00
Christoph Hegemann
45b5ed8227
perf: Find syntactic matches concurrently (#63937)
Closes
https://linear.app/sourcegraph/issue/GRAPH-764/filter-syntactic-results-in-parallel

Cuts search time for large results in half. A lot more gains when
combined with a smarter GitTreeTranslator

## Test plan

Covered by existing tests
2024-07-19 10:09:18 +02:00
Quinn Slack
85359ac01d
allow non-site admins to list their orgs' members on dotcom (#63934)
Previously, only site admins could see the members of an org, even of
orgs that they were a member of. This restriction does not make any
sense and makes the orgs feature broken on dotcom.

## Test plan

Added test.
2024-07-19 00:37:03 -07:00
Warren Gifford
43df26fab3
feature/release: update sg release cut to automate stitch graph gen and release branch creation (#63794)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

Resolve:
[https://linear.app/sourcegraph/issue/REL-253/bug-automate-the-stitched-migration-graph-bazel-archive-generation](https://linear.app/sourcegraph/issue/REL-253/bug-automate-the-stitched-migration-graph-bazel-archive-generation)

## Test plan
Tested by running `go run ./dev/sg release cut --version “5.7.0"`

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Anish Lakhwara <anish+git@lakhwara.com>
Co-authored-by: Anish Lakhwara <anish+github@lakhwara.com>
2024-07-18 23:15:04 -07:00
Felix Kling
0bf40cd83b
fix(svelte): Fix and cleanup compare page (#63928)
I just noticed that the revision pickers on the compare page don't work.
That's because I made a last minute change to rename the parameter but
forgot to acutally update the parameter when constructing the URL.

This also makes two additional changes:
- Remove `{@debug ...}` expression that was accidentally left in (I feel
like Svelte should remove this in prod builds).
- Adds a `display` prop to button group, and the rev picker, which works
the same as in `Button`. Setting `width: 100%` as done previously causes
wrapping on the compare page. I don't think inline elements should be
set to 100% width. But without it the button doesn't stretch in the
sidebar. This new prop allows the caller to influence this behavior.

| Before | After |
|--------|--------|
|
![2024-07-19_00-59](https://github.com/user-attachments/assets/53b9942d-ebf9-4677-8c65-21cd38e78e44)
|
![2024-07-19_01-05](https://github.com/user-attachments/assets/c38ee133-7ee7-4923-ae22-caad9e2472f1)
|

## Test plan

Tested the compare page and verified that the revision picker stretches
in the sidebar.
2024-07-19 05:43:48 +00:00
Stephen Gutekanst
dca1b9694d
self hosted models (#63899)
This PR is stacked on top of all the prior work @chrsmith has done for
shuffling configuration data around; it implements the new "Self hosted
models" functionality.

## Configuration

Configuring a Sourcegraph instance to use self-hosted models basically
involves adding some configuration like this to the site config (if you
set `modelConfiguration`, you are opting in to the new system which is
in early access):

```
  // Setting this field means we are opting into the new Cody model configuration system.
  "modelConfiguration": {
    // Disable use of Sourcegraph's servers for model discovery
    "sourcegraph": null,

    // Create two model providers
    "providerOverrides": [
      {
        // Our first model provider "mistral" will be a Huggingface TGI deployment which hosts our
        // mistral model for chat functionality.
        "id": "mistral",
        "displayName": "Mistral",
        "serverSideConfig": {
          "type": "huggingface-tgi",
          "endpoints": [{"url": "https://mistral.example.com/v1"}]
        },
      },
      {
        // Our second model provider "bigcode" will be a Huggingface TGI deployment which hosts our
        // bigcode/starcoder model for code completion functionality.
        "id": "bigcode",
        "displayName": "Bigcode",
        "serverSideConfig": {
          "type": "huggingface-tgi",
          "endpoints": [{"url": "http://starcoder.example.com/v1"}]
        }
      }
    ],

    // Make these two models available to Cody users
    "modelOverridesRecommendedSettings": [
      "mistral::v1::mixtral-8x7b-instruct",
      "bigcode::v1::starcoder2-7b"
    ],

    // Configure which models Cody will use by default
    "defaultModels": {
      "chat": "mistral::v1::mixtral-8x7b-instruct",
      "fastChat": "mistral::v1::mixtral-8x7b-instruct",
      "codeCompletion": "bigcode::v1::starcoder2-7b"
    }
  }
```

More advanced configurations are possible, the above is our blessed
configuration for today.

## Hosting models

Another major component of this work is starting to build up
recommendations around how to self-host models, which ones to use, how
to configure them, etc.

For now, we've been testing with these two on a machine with dual A100s:

* Huggingface TGI (this is a Docker container for model inference, which
provides an OpenAI-compatible API - and is widely popular)
* Two models:
* Starcoder2 for code completion; specifically `bigcode/starcoder2-15b`
with `eetq` 8-bit quantization.
* Mixtral 8x7b instruct for chat; specifically
`casperhansen/mixtral-instruct-awq` which uses `awq` 4-bit quantization.

This is our 'starter' configuration. Other models - specifically other
starcoder 2, and mixtral instruct models - certainly work too, and
higher parameter versions may of course provide better results.

Documentation for how to deploy Huggingface TGI, suggested configuration
and debugging tips - coming soon.

## Advanced configuration

As part of this effort, I have added a quite extensive set of
configuration knobs to to the client side model configuration (see `type
ClientSideModelConfigOpenAICompatible` in this PR)

Some of these configuration options are needed for things to work at a
basic level, while others (e.g. prompt customization) are not needed for
basic functionality, but are very important for customers interested in
self-hosting their own models.

Today, Cody clients have a number of different _autocomplete provider
implementations_ which tie model-specific logic to enable autocomplete,
to a provider. For example, if you use a GPT model through Azure OpenAI,
the autocomplete provider for that is entirely different from what you'd
get if you used a GPT model through OpenAI officially. This can lead to
some subtle issues for us, and so it is worth exploring ways to have a
_generalized autocomplete provider_ - and since with self-hosted models
we _must_ address this problem, these configuration knobs fed to the
client from the server are a pathway to doing that - initially just for
self-hosted models, but in the future possibly generalized to other
providers.

## Debugging facilities

Working with customers in the past to use OpenAI-compatible APIs, we've
learned that debugging can be quite a pain. If you can't see what
requests the Sourcegraph backend is making, and what it is getting
back.. it can be quite painful to debug.

This PR implements quite extensive logging, and a `debugConnections`
flag which can be turned on to enable logging of the actual request
payloads and responses. This is critical when a customer is trying to
add support for a new model, their own custom OpenAI API service, etc.

## Robustness

Working with customers in the past, we also learned that various parts
of our backend `openai` provider were not super robust. For example, [if
more than one message was present it was a fatal
error](https://github.com/sourcegraph/sourcegraph/blob/main/internal/completions/client/openai/openai.go#L305),
or if the SSE stream yielded `{"error"}` payloads, they would go
ignored. Similarly, the SSE event stream parser we use is heavily
tailored towards [the exact response
structure](https://github.com/sourcegraph/sourcegraph/blob/main/internal/completions/client/openai/decoder.go#L15-L19)
which OpenAI's official API returns, and is therefor quite brittle if
connecting to a different SSE stream.

For this work, I have _started by forking_ our
`internal/completions/client/openai` - and made a number of major
improvements to it to make it more robust, handle errors better, etc.

I have also replaced the usage of a custom SSE event stream parser -
which was not spec compliant and brittle - with a proper SSE event
stream parser that recently popped up in the Go community:
https://github.com/tmaxmax/go-sse

My intention is that after more extensive testing, this new
`internal/completions/client/openaicompatible` provider will be more
robust, more correct, and all around better than
`internal/completions/client/openai` (and possibly the azure one) so
that we can just supersede those with this new `openaicompatible` one
entirely.

## Client implementation

Much of the work done in this PR is just "let the site admin configure
things, and broadcast that config to the client through the new model
config system."

Actually getting the clients to respect the new configuration, is a task
I am tackling in future `sourcegraph/cody` PRs.

## Test plan

1. This change currently lacks any unit/regression tests, that is a
major noteworthy point. I will follow-up with those in a future PR.
* However, these changes are **incredibly** isolated, clearly only
affecting customers who opt-in to this new self-hosted models
configuration.
* Most of the heavy lifting (SSE streaming, shuffling data around) is
done in other well-tested codebases.
2. Manual testing has played a big role here, specifically:
* Running a dev instance with the new configuration, actually connected
to Huggingface TGI deployed on a remote server.
* Using the new `debugConnections` mechanism (which customers would use)
to directly confirm requests are going to the right places, with the
right data and payloads.
* Confirming with a new client (changes not yet landed) that
autocomplete and chat functionality work.

Can we use more testing? Hell yeah, and I'm going to add it soon. Does
it work quite well and have small room for error? Also yes.

## Changelog

Cody Enterprise: added a new configuration for self-hosting models.
Reach out to support if you would like to use this feature as it is in
early access.

---------

Signed-off-by: Stephen Gutekanst <stephen@sourcegraph.com>
2024-07-19 01:34:02 +00:00
Quinn Slack
b4e03f45b0
Prompt Library (#63872)
The Prompt Library lets you create, share, and browse chat prompts for
use with Cody. Prompts are owned by users or organizations, and site
admins can make prompts public so that all users on the instance can see
and use them.

A prompt is just plain text for now, and you can see a list of prompts
in your Prompt Library from within Cody chat
(https://github.com/sourcegraph/cody/pull/4903).

See https://www.loom.com/share/f3124269300c481ebfcbd0a1e300be1b.

Depends on https://github.com/sourcegraph/cody/pull/4903.


![image](https://github.com/user-attachments/assets/d1098809-f7ff-4233-8ecb-9bc53ad4dbb2)


## Test plan

Add a prompt on the web. Ensure you can access it from Cody.

## Changelog

- The Prompt Library lets you create, share, and browse chat prompts for
use with Cody. Prompts are owned by users or organizations, and site
admins can make prompts public so that all users on the instance can see
and use them. To use a prompt from your Prompt Library in Cody, select
it in the **Prompts** dropdown in the Cody chat message field.
2024-07-18 16:04:55 -07:00
Geoffrey Gilmore
57de59cb3c
internal/database/sub_repo_permissions: modify store to be able to insert ip based permissions (#63811)
Closes https://linear.app/sourcegraph/issue/SRC-459/
Closes 

This PR adds support for saving and retreiving the IP addressess
associated with each path rule in the sub_repo_permissions store.

It does this by:

**Adding a new permissions type to the internal/authz package**:


1be7df6d79/internal/authz/iface.go (L52-L96)

**Adding new `*WithIPs` versions of all the setter and getter methods** 

The new setter methods uses the above `authz.SubRepoPermissionsWithIPs`
type that write to the appropriate `ips` column in the DB.

The new getter methods retrieve the ip addresses associated with each
path entry. However, here there is an additional complication: It's
possible for someone to call the `*WithIPs` getters when the ips column
is still NULL (indicating that the perforce syncer hasn't been updated /
ran in order to save the IP addresses from the protection table yet.

| repo_id | user_id | version | updated_at | paths | ips |
|---------|---------|---------|------------|-------|-----|
| 1 | 1 | 1 | 2023-07-01 10:00:00 | {`"/depot/main/..."`,
`"/depot/dev/..."`, `"-/depot/secret/..."`} | NULL |
| 2 | 1 | 1 | 2023-07-01 11:00:00 | {`"/depot/public/..."`,
`"-/depot/private/..."`} | NULL |

In order to address this, the getters each have a `backfill` boolean
that allows the caller to choose the behavior that they want.

- If `backfill = true`, the paths without IP entries will be returned
with a `*` (wildcard) IP indicating that any client IP address is okay.
(This is effectively the behavior we have today since we don't check IPs
for sub_repo_permisisons). I imagine this can be used when callers don't
care about enforcing IP-based permissions (such as when IP address
enforcement is disabled in site configuration).

- If `backfill = false`, if the IPs column is NULL - an error is
returned instead of backfilling ("The IP addresses associated with this
sub-repository-permissions entry have not been synced yet."). This
allows for callers that care about IP address enforcement to know
_explicitly_ if the IP address information hasn't been updated yet - so
we can't know whether or not the user is able to view the file (e.g when
IP based enforcement is enabled).


**Ensuring that the old setter methods set the IPs column to NULL**: 

self-explanatory, if someone uses the non `*WithIP` variants of the
setters, we want to ensure that we zero out that column so that we don't
leave stale / inconsistent information for those Path entries.

---

Overall, the design this adds the new IP address functionality without
having to immediately update all the call sites in the codebase to force
them to interpret all this information (which would make for a
gargantuan PR). Eventually, we should be able to simply delete the old
versions of the setters/getters once the IP address functioanlity has
been threaded through everywhere.

## Test plan

Extensive unit tests. 

For each new setter and getter, I added unit tests that tested along all
of the following dimenisons:

- **initial store state**: empty database, database seeded with
permissions with no IP information (paths column only), database seeded
with permissions that have the IP information synced
- **insertion method**: was the data for the test inserted **with IP
information** (using the `withIP` variant of upsert, etc.), or was it
inserted with the old legacy way with no ip information
- **retreieval method**: was the data reterived with the legacy getters
(that don't look at the IP information), with the new IP getters that
either backfill (if the IP information for that paths entry hasn't been
synced yet, it will return an `*` for that entry), or avoids backfilling
(will return the information in the IPs column, or hard-error)?
## Changelog

- The sub_repository_permissions_ database store can now save and
retrieve the IP addresses associated with each path rule.
2024-07-18 14:05:30 -07:00
Geoffrey Gilmore
12570e4ee4
Revert "fix(sg): resolve overwrite env ordering in sg (#63838)" (#63924)
https://github.com/sourcegraph/sourcegraph/pull/63838 accidentally broke
the local-dev site configuration workflow (the site-configuration from
local dev was replaced with a stock configuration).

 Reverting this is probably the fastest way to resolve this. 

See https://sourcegraph.slack.com/archives/C07KZF47K/p1721329375844059
for more context.

## Test plan

CI

## Changelog

- The flawed env overwriting logic in sg from
https://github.com/sourcegraph/sourcegraph/pull/63838 has been reverted.
2024-07-18 20:46:35 +00:00
Quinn Slack
fcdcfef706
add saved search visibility, draft, and timestamps (#63909)
**Public saved searches will let us make global saved searches for
dotcom and for customers to help them discover and share awesome search
queries!**

Saved searches now have:

- Visibility (public vs. secret). Only site admins may make a saved
search public. Secret saved searches are visible only to their owners
(either a user, or all members of the owning org). A public saved search
can be viewed by everyone on the instance.
- Draft status: If a saved search's "draft" checkbox is checked, that
means that other people shouldn't use that saved search yet. You're
still working on it.
- Timestamps: The last user to update a saved search and the creator of
the saved search are now recorded.

Also adds a lot more tests for saved search UI and backend code.


![image](https://github.com/user-attachments/assets/a6fdfa54-61c5-4a0f-9f04-1bdf34ae3ad4)

![image](https://github.com/user-attachments/assets/a29567a0-9cfa-4535-99b6-7ffb4aea4102)

![image](https://github.com/user-attachments/assets/e287e18c-0b88-451d-b1c8-a26987e7ec47)


## Test plan

Create a saved search. Ensure it's in secret visibility to begin with.
As a site admin, make it public. Ensure other users can view it, and no
edit buttons are shown. Try changing visibility back and forth.

## Changelog

- Saved searches can now be made public (by site admins), which means
all users can view them. This is a great way to share useful search
queries with all users of a Sourcegraph instance.
- Saved searches can be marked as a "draft", which is a gentle indicator
that other people shouldn't use it yet.
2024-07-18 13:37:41 -07:00
Felix Kling
f983676e65
feat(svelte): Improve commit page layout on mobile (#63920)
I noticed that the commit page doesn't render well on mobile when the
commit has a commit message.

This commit refactors how the `Commit` component is rendered, including
on mobile, which affects both the commit**s** and the commit page.

The two most important changes:

- The component now uses CSS grid to be more flexible about how
individual elements are arranged.
- On mobile we don't show expand the message inline anymore but instead
show it full screen. I think that works well for the commits list too
because now you can open and read a longer commit message without having
to scroll the commits list itself.

## Test plan

Manually inspecting the commits and commit pages. Opened a long commit
message to test that the message is properly scrollable.
2024-07-18 22:02:16 +02:00
James Cotter
4c040347ec
sg/msp: enable alerting by default for production projects (#63912)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Opsgenie alert notifications for critical alerts should be enabled by
default for production projects or where `env.alerting.opsgenie` is set
to true.

Closes CORE-223
## Test plan
Tested locally by running `sg msp gen` for a `prod` env which doesn't
have an alerting config and verifying that notification suppression was
disabled

Set `env.alerting.opsgenie` to false which enabled suppression again.

No changes to `test` environments unless `env.alerting.opsgenie` is set
to true.
2024-07-18 20:57:38 +01:00
Geoffrey Gilmore
14137ed9df
feature/db/sub_repo_perms: add IPs column to sub repo perms (#63771)
This PR modifies the sub_repo_permissions database to store the ip
addresses associated with each Perforce path rule, as part of the IP
based sub repo permissions work.

The new IP column is implemetned as a []text similar to the path column.
The IP address associated with `paths[0]` is stored in the ips column in
`ips[0]`.

For example, the follownig proections table 

```
Protections:
    read     user     emily   *                    //depot/elm_proj/...
    write    group    devgrp  *                    //...
    write    user     *       192.168.41.0/24     -//...
    write    user     *       [2001:db8:1:2::]/64 -//...
    write    user     joe     *                   -//...
    write    user     lisag   *                   -//depot/...
    write    user     lisag   *                    //depot/doc/...
    super    user     edk     *                    //...
```

turns into the following rows in the sub_repo_permissions table

| repo_id | user_id | version | updated_at | paths | ips |
|---------|---------|---------|------------|-------|-----|
| 1 | 1 | 1 | 2023-07-01 10:00:00 | {`"//depot/elm_proj/..."`} | {`"*"`}
|
| 1 | 2 | 1 | 2023-07-01 10:00:00 | {`"//..."`} | {`"*"`} |
| 1 | 3 | 1 | 2023-07-01 10:00:00 | {`"-//..."`} | {`"192.168.41.0/24"`}
|
| 1 | 4 | 1 | 2023-07-01 10:00:00 | {`"-//..."`} |
{`"2001:db8:1:2::]/64"`} |
| 1 | 5 | 1 | 2023-07-01 10:00:00 | {`"-//..."`} | {`"*"`} |
| 1 | 6 | 1 | 2023-07-01 10:00:00 | {`"-//depot/..."`,
`"//depot/doc/..."`} | {`"*"`, `"*"`} |
| 1 | 7 | 1 | 2023-07-01 10:00:00 | {`"//..."`} | {`"*"`} |

## Test plan

The unit test for the sub_repository_permissions store PR that is built
on this PR:
https://app.graphite.dev/github/pr/sourcegraph/sourcegraph/63811/internal-database-sub_repo_permissions-modify-store-to-be-able-to-insert-ip-based-permissions

## Changelog

- The sub_repo_permissions table now has an ips column to store the
associated IP address associated with each path rule.
2024-07-18 12:54:54 -07:00
Felix Kling
462ff95169
feat(svelte): Change branch and tags page design, including mobile (#63914)
The branches page didn't work well on mobile and neither did the tags
page if long tag names were present.

This commit changes how the information is displayed and rendered,
especially on mobile.

I also added additional links to each row to make navigating to relevant
places easier.

## Test plan
 
Manual inspection of pages in various screen sizes.
2024-07-18 21:33:51 +02:00
Camden Cheek
f7511c4a59
Svelte: implement new reference panel against new Usages API (#63724)
This implements a first pass at the new references panel built against
the new usages API.
2024-07-18 13:32:45 -06:00
Quinn Slack
f657f99a62
withAuthenticatedUser: use react-router-dom hooks & add test (#63906)
This improves the typings to remove some inscrutable inferred types and
some weird type errors if you didn't use React.PropsWithChildren. Also
refactors the code and exposes a new component AuthenticatedUserOnly
that's simpler and can be used when you don't need to do prop
propagation of authenticatedUser.

## Test plan

CI
2024-07-18 12:30:36 -07:00
Camden Cheek
d91fab39e2
Blame: fix some issues with the stream (#63865)
Contributes to SRCH-738

Notably, this does not yet identify the root cause of SRCH-738, but it
does identify and fix some confounding bugs. It's possible that these
actually also _cause_ some of the issues in SRCH-738, but I wanted to at
least push these to dotcom, where we can reproduce some of the
weirdness. At the very least, it doesn't explain the auth errors being
reported.
2024-07-18 12:53:37 -06:00
Michael Bahr
d5292caa82
chore: re-enable e2e tests for web-sveltekit (#63910)
The goal of this PR is to increase the stability of web-sveltekit
e2e-tests so that we don't have to rely on manual runs anymore. They
have previously been disabled due to a high number of failures:
https://github.com/sourcegraph/sourcegraph/pull/63874

---

To improve the stability of web-sveltekit e2e-tests, I used `sg ci bazel
test //client/web-sveltekit:e2e_test --runs_per_test=N` with N=5,10,15
to see which tests break under different levels of pressure on the
machine. The logs looked like it was mostly timeouts, that got worse
when increasing N. That means we can check where tests will break due to
timeouts, but we don't really need to raise timeouts so far that it
would work with N=20.

With N=5, 10 we get a good understanding if our timeouts are high
enough.

You can see two CI runs here after applying higher timeouts and skipping
a consistently failing test:

- N=5:
https://buildkite.com/sourcegraph/sourcegraph/builds/283011/waterfall
- N=10:
https://buildkite.com/sourcegraph/sourcegraph/builds/283013/waterfall

---

From logs of some other run that I don't have the link to anymore, we
can see that some tests take up to 50s so a timeout of 60s (instead of
the default 30s) for CI should be a good new ceiling.

```
Slow test file: [chromium] › src/routes/[...repo=reporev]/(validrev)/(code)/-/blob/[...path]/page.spec.ts (48.9s)
--
  | Slow test file: [chromium] › src/routes/[...repo=reporev]/(validrev)/(code)/page.spec.ts (45.0s)
  | Slow test file: [chromium] › src/routes/search/page.spec.ts (40.6s)
  | Slow test file: [chromium] › src/routes/[...repo=reporev]/(validrev)/(code)/-/tree/[...path]/page.spec.ts (31.7s)
  | Slow test file: [chromium] › src/routes/layout.spec.ts (31.5s)

```

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-18 19:31:02 +02:00
Craig Furman
0491839942
fix(appliance): resource kind present on reconciler logs (#63919)
It turns out that Kubernetes objects constructed using client-go don't
know their own TypeMeta. There is code in client-go that figures out
which resource-scoped HTTP path to call on the kube-apiserver by looking
up a mapping of Go object kinds to k8s kinds. A similar facility appears
to be exposed to the user by apiutil.GVKForObject().

Closes
https://linear.app/sourcegraph/issue/REL-275/reconciler-logs-dont-contain-resource-metadata
2024-07-18 13:29:18 -04:00
Robert Lin
f6ce941610
feat/sg: do not persist external secrets (#63890)
Secrets fetched from GSM should probably not be stored locally. As we
increase the usage of fetching external secrets, this stuff is
increasingly sensitive, particularly for SAMS stuff - every time it's
used, we should ensure that the user has the required permissions, and
also only store external secrets in-memory.

It looks like several other callsites make use of the persistence of
other secrets e.g. those prompted from users, so this change
specifically targets the `GetExternal` method. Additionally, I also
added a check on load to delete any legacy external secrets that are
stored to disk on load - we can remove this after a few weeks.

## Test plan

Unit tests asserts old behaviour and new desired behaviour

`sg start -cmd cody-gateway` uses external secrets and works as expected

After running `sg`, `sg secret list` has no external secrets anymore
2024-07-18 10:04:24 -07:00
Bolaji Olajide
857ade25db
fix(sg): resolve overwrite env ordering in sg (#63838)
Closes
[DINF-58](https://linear.app/sourcegraph/issue/DINF-58/overwrite-ordering-in-sg)


https://github.com/user-attachments/assets/d8e59a5f-9390-47f7-a6a7-9ccbf97423f8

## Test plan

- Add a `commandset` to the `sg.config.overwrite.yaml`
- This commandset should depend on an existing command in the
`sg.config.yaml` file.
- The commandset should also include an `env var` that should override
what's set in the `command` contained in the `sg.config.yaml` file.
- Running `sg start <commandset name>` should allow the env ordering
matrix shown below

```
Priority: overwrite.command.env > overwrite.commandset.env > command.env > commandset.env.
```

## Changelog

N/A
2024-07-18 12:01:04 -05:00
Jason Hawk Harris
a395ef7dfc
Add separate shadow value for hovercards (#63918)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
The box-shadow value for code intel hover cards is too dark, and makes
the content directly below more difficult to read.

Before:
![Screenshot 2024-07-18 at 9 36 53
AM](https://github.com/user-attachments/assets/a07907e7-53c4-49d7-a63a-a286f9b74235)

After: 
![Screenshot 2024-07-18 at 9 37 16
AM](https://github.com/user-attachments/assets/e9ce868c-6050-4494-83a7-ce55182349a0)

I added a new scss variable so it can be re-used. I'm not sure I've put
it in the best place in the codebase though, let me know if you think
there's a better location for it.

## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
Manual/visual testing
## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-18 10:12:02 -05:00
Noah S-C
b7dac3b808
fix(ci): only emit bazel execlog artifact for 'test' commands (#63916)
Delivery Manifest step has started to run `bazel build` commands, in them clobbering our execlog artifacts. We should only emit it for the test buildkite jobs (at least for the time being), as it currently doesnt make sense for e.g. the image push jobs which contain multiple invocations

## Test plan

CI

## Changelog
2024-07-18 15:17:12 +01:00
Ólafur Páll Geirsson
51bc688ec9
fix(cody): allow pre-release versions for clients (#63913)
Previously, Sourcegraph Enterprise instances with context filters
enabled would reject requests from clients that specified a pre-release
version like 1.2.0-alpha. This PR makes the version check more relaxed
to permit versions like that.

Caught by @taras-yemets in
https://github.com/sourcegraph/sourcegraph/pull/63855/files#r1682690612
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

See updated test case.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-18 13:17:07 +00:00
Jean-Hadrien Chabran
ff21dd3cc8
chore(local): hotfix when local client assets become too big (#63807)
Follow-up to
https://sourcegraph.slack.com/archives/C07KZF47K/p1720639713491779?thread_ts=1720636753.404169&cid=C07KZF47K

Basically, if we see that the local assets are above 500mb, we just nuke
it. It's a bandage btw. The `.gitkeep` is there so it doesn't break the
build because there's nothing to embed.

@eseliger and @burmudar can you test this a bit further and land it if
it's all good? My tests are good, but I don't want to hastily land
something and go in PTO five seconds before I'm out for two weeks.

## Test plan

Locally tested.

---------

Co-authored-by: William Bezuidenhout <william.bezuidenhout@sourcegraph.com>
2024-07-18 14:20:39 +02:00
Rafał Gajdulewicz
7211c8cdb2
[sg] Make rfc command use private RFCs by default (#63902)
This PR changes the `sg rfc` command to introduce a new flag `--public`
(previously, an implicit default) and removes the flag `--private` (new
default).

This change implements part of our new approach to RFCs (private by
default,
[context](https://sourcegraph.slack.com/archives/C03L2R35ENL/p1719013625952019)
[need to
follow-up](https://sourcegraph.slack.com/archives/C01GNBB34FR/p1720813994240309?thread_ts=1720626835.727909&cid=C01GNBB34FR)).

## Test plan

- ran `sg rfc create "test new default"` and a private
[RFC](https://docs.google.com/document/d/1gGrejPvHQaeKPrHr4PW_XxdArZQ4iUAWxlhkjglaNQc/edit#heading=h.trqab8y0kufp)
was created
- ran `sg rfc --public create "test public"` and a public
[RFC](https://docs.google.com/document/d/1K_ElZWyvCNV3QMGoBr9-h4L0h_2wswbVauEjmzD6shk/edit#heading=h.trqab8y0kufp)
was created
- ran `sg rfc list` and private RFCs were listed
- ran `sg rfc --public list` and public RFCs were listed
2024-07-18 14:12:28 +02:00
Ólafur Páll Geirsson
d4653a880c
fix(cody): remove client check for context filters (#63855)
Fixes CODY-2888

Previously, Sourcegraph Enterprise instances with context filters
enabled rejected requests from all unknown clients out of concern that
they might not respect context filters. This behavior makes it
incredibly impractical to release now agent-based clients (CLI, Eclipse,
Visual Studio, Neovim, ..) that do respect context filters out of the
box thanks to the reused logic in the Cody agent.

This logic suffers from both false positives and false negatives:

- False negatives: upcoming Cody clients (CLI, Eclipse, Visual Studio)
already support context filters out of the box thanks to using the Cody
agent but they can't send requests unless we add a special case to them.
It may require months for these clients to wait for all Enterprise
instances to upgrade to a version that adds exceptions for their name.
- False positive: a malicious client can always fake that it's
"jetbrains" with a valid version number even if the client doesn't
respect context filters. This gives a false sense of security because it
doesn't prevent malicious traffic from bypassing context filters. In
fact, I am leaning towards using the

Now, with this change, Sourcegraph Enterprise instances only reject
requests from old versions of Cody clients that are known to not support
context filters. This ensures we never have false positives or false
negatives.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan
See updated test case which accepts a request from an unknown "sublime"
client.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-18 11:44:05 +00:00
Craig Furman
c88b57020f
fix(appliance): always self-update to latest (#63848)
Instead of a a maximum of 2 minor versions beyond the deployed
Sourcegraph instance.

The main advantage of removing the 2-minor-version constraint, is that
it allows admins to always be able to update to the latest SG with one
click, instead of having to repeat that process through intermediate
versions if they have fallen far behind.
2024-07-18 12:38:11 +01:00
Taras Yemets
277648821c
chore(cody): allow setting "cody.contextFilters" in site config without feature flag (#63881)
<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->
Cody context filters support is now supported by default by all Cody
clients (see also
[this](https://sourcegraph.slack.com/archives/C05AGQYD528/p1721138647380249)
thread). Thus we no longer need to gate instance admins from setting
`"cody.contextFilters" in the site config as we know there's suffient
feature support on the client side.
This PR is technically a revert of
https://github.com/sourcegraph/sourcegraph/pull/62231.

Remove feature flag from s2 config:
- https://github.com/sourcegraph/cloud/pull/12001

<img width="640" alt="Screenshot 2024-07-17 at 18 42 09"
src="https://github.com/user-attachments/assets/10639118-b866-4ac2-8838-5f6f036baf11">
<img width="640" alt="Screenshot 2024-07-17 at 18 42 40"
src="https://github.com/user-attachments/assets/a4a0ca14-052d-4ef3-97a7-2b71b84f36ec">

## Test plan
- CI
- Tested manually: "cody.contextFilters" can be st in the site config
without having `cody-context-filters-enabled` feature flag enabled


<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Olafur Geirsson <olafurpg@gmail.com>
2024-07-18 14:27:55 +03:00
Quinn Slack
747abc98b1
query Repository.id to support Apollo Client caching (#63905)
Otherwise Apollo Client complains that it does not know how to cache the
result because it does not know which repository ID to associate the
result with.

## Test plan

CI
2024-07-18 03:53:50 -07:00
Rafał Gajdulewicz
8af830a2a8
Unify naming of used/ignored context (#63903)
Replaces the use of discarded/unused/filtered with a consistent use of
ignored.

## Test plan

- tested locally
2024-07-18 10:34:29 +02:00
Michael Bahr
f61e637062
feat(code insights): language stats speed improvements by using archive loading (#62946)
We previously improved the performance of Language Stats Insights by
introducing parallel requests to gitserver:
https://github.com/sourcegraph/sourcegraph/pull/62011

This PR replaces the previous approach where we would iterate through
and request each file from gitserver with an approach where we request
just one archive. This eliminates a lot of network traffic, and gives us
an additional(!) performance improvement of 70-90%.

Even repositories like chromium (42GB) can now be processed (on my
machine in just one minute).

---

Caching: We dropped most of the caching, and kept only the top-level
caching (repo@commit). This means that we only need to compute the
language stats once per commit, and subsequent users/requests can see
the cached data. We dropped the file/directory level caching, because
(1) the code to do that got very complex and (2) we can assume that most
repositories are able to compute within the 5 minutes timeout (which can
be increase via the environment variable `GET_INVENTORY_TIMEOUT`). The
timeout is not bound to the user's request anymore. Before, the frontend
would request the stats up to three times to let the computation move
forward and pick up where the last request aborted. While we still have
this frontend retry mechanism, we don't have to worry about an
abort-and-continue mechanism in the backend.

---

Credits for the code to @eseliger:
https://github.com/sourcegraph/sourcegraph/issues/62019#issuecomment-2119278481

I've taken the diff, and updated the caching methods to allow for more
advanced use cases should we decide to introduce more caching. We can
take that out again if the current caching is sufficient.

Todos:

- [x] Check if CI passes, manual testing seems to be fine
- [x] Verify that insights are cached at the top level

---

Test data:

- sourcegraph/sourcegraph: 9.07s (main) -> 1.44s (current): 74% better
- facebook/react: 17.52s (main) -> 0.87s (current): 95% better
- godotengine/godot: 28.92s (main) -> 1.98s (current): 93% better
- chromium/chromium: ~1 minute: 100% better, because it didn't compute
before

## Changelog

- Language stats queries now request one archive from gitserver instead
of individual file requests. This leads to a huge performance
improvement. Even extra large repositories like chromium are now able to
compute within one minute. Previously they timed out.

## Test plan

- New unit tests
- Plenty of manual testing
2024-07-18 08:40:48 +02:00
Christoph Hegemann
c38e0b1687
refactor(codeintel): Extracts a MappedIndex abstraction over uploads (#63781)
Precursor for
https://linear.app/sourcegraph/issue/GRAPH-735/test-syntactic-usages

This PR introduces the `MappedIndex` abstraction, which wraps up an
upload with a target commit. Its APIs then take care of mapping upload
relative paths and repo relative paths, and ranges across commits.

My main motivation for making this change is that I can now test this
logic in isolation (which this PR does), and also have an interface that
is easy to fake and use to test syntactic usages.

## Test plan

Added unit tests for the `MappedIndex` component, manual testing of the
GraphQL APIs show no changes in the syntactic usages output between this
PR and master.
2024-07-18 05:54:48 +02:00
Camden Cheek
dfb55a275e
Svelte: fix css selector (#63896)
Fixes a couple of small style changes after rolling out the mobile version.
2024-07-17 21:47:19 -03:00
Robert Lin
dbf420bb8c
fix/enterpriseportal: drop old gorm fk constraints (#63864)
Turns out, `gorm` does not auto-migrate constraints you've removed from
the struct schema. You must drop them by hand, or run the commands to
drop them explicitly.

## Test plan

```
sg start -cmd enterprise-portal
```

```
\d+ enterprise_portal_*
```

then, comment the custom migrations, and run `sg start -cmd
enterprise-portal` again to re-do the migrations. The output of `\d+`
matches. Unexpected constraints are gone.
2024-07-17 14:16:02 -07:00
Felix Kling
8661226443
feat(svelte): Add compare page (#63850)
This commit adds the Svelte version of the compare page. Now that we
have a revision picker this was easy to implement.

A couple of notes:
- The URL parameter is a rest parameter ([...spec]) because revisions
can contain slashes, and we don't encode those.
- I changed the API of the revision selector so that it works on pages
that don't have `resolvedRevision` available (also we never needed the
`repo` property from that object), and to provide custom select
handlers.
- Moved the revision to lib since it's used on various different pages.
- Unlike the React version this version
  - Provides forward/backward buttons to browse the commit list
  - Uses infinity scrolling to load the next diffs
- Doesn't use a different style for the commit list. I experimented with
adding a "compact" version of the commit but it didn't feel quite right.
I'm sure we'll eventually redesign this.
- The `filePath` parameter is supported (for backwards compatibility)
but we don't use it anywhere atm.

(note that the avatar size has changed since the video was recorded;
it's larger now)


## Test plan

Manual testing.
2024-07-17 23:02:17 +02:00
William Bezuidenhout
26c2b33262
sg: check for nil multiError (#63889)
Fixes https://github.com/sourcegraph/devx-support/issues/1097

## Test plan
Before
```
👉 [      step] Pretending to run step "github:pr"
   [ github:pr] set -eu
   [ github:pr] gh pr create \
   [ github:pr]   --fill \
   [ github:pr]   --draft \
   [ github:pr]   --title "(internal) release_patch: build v5.5.1220" \
   [ github:pr]   --body "Test plan: automated release PR, CI will perform additional checks"
   [ github:pr] echo "🚢 Please check the associated CI build to ensure the process completed".
   [ github:pr]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x20 pc=0x1059c1380]

goroutine 42 [running]:
github.com/sourcegraph/sourcegraph/dev/sg/internal/analytics.processEvents({0x10b4a71d8, 0x1400188eaf0}, 0x1400330a140, {{0x10b482ed8?, 0x140033141f8?}}, 0x140033080c0)
        github.com/sourcegraph/sourcegraph/dev/sg/internal/analytics/background.go:107 +0x320
main.init.func52.BackgroundEventPublisher.4({0x10b4a71d8, 0x1400188eaf0}, 0x1400330a140)
        github.com/sourcegraph/sourcegraph/dev/sg/internal/analytics/background.go:30 +0x14c
github.com/sourcegraph/sourcegraph/dev/sg/internal/background.Run.func1()
        github.com/sourcegraph/sourcegraph/dev/sg/internal/background/background.go:62 +0x74
created by github.com/sourcegraph/sourcegraph/dev/sg/internal/background.Run in goroutine 1
        github.com/sourcegraph/sourcegraph/dev/sg/internal/background/background.go:57 +0x174
```
After
```
👉 [      step] Pretending to run step "github:pr"
   [ github:pr] set -eu
   [ github:pr] gh pr create \
   [ github:pr]   --fill \
   [ github:pr]   --draft \
   [ github:pr]   --title "(internal) release_patch: build v5.5.1220" \
   [ github:pr]   --body "Test plan: automated release PR, CI will perform additional checks"
   [ github:pr] echo "🚢 Please check the associated CI build to ensure the process completed".
   [ github:pr]

deploy-sourcegraph-k8s on  main [?⇕] via 🐹 v1.22.3 took 5s
```

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-17 19:53:41 +00:00
Chris Smith
3cb1c4528d
Update CodyLLMConfiguration GraphQL object to be modelconfig aware (#63886)
We recently updated the completions APIs to use the `modelconfig` system
for managing LLM model configuration. Behind the scenes, we
automatically converted the existing site configuration ("completions
config") into the newer format so things work as expected.

However, the GraphQL view of the Sourcegraph instance's LLM
configuration was not updated to use the `modelconfig` system. And so fi
the site admin and opted into using the new-style of configuration data,
the data returned would be all sorts of wrong.

(Because the GraphQL handler looked for the "completions config" part of
the site config, and not the newer "model configuration" section.)

This PR updates the `CodyLLMConfiguration` GraphQL resolver to return
the data from the modelconfig component of the Sourcegraph instance.

Some careful refactoring was needed to avoid a circular dependency in
the Go code. So the resolver's type _declaration_ is in the
`graphqlbackend` package. But it's _definition_ is in
`internal/modelconfig`.

## Test plan

I only tested these changes manually.

If you open the Sourcegraph instance's API console, this is the GraphQL
query to serve all of the data:

```gql
{
  site {
    codyLLMConfiguration {
      chatModel
      fastChatModel
      completionModel
      provider
      disableClientConfigAPI
      chatModelMaxTokens
      fastChatModelMaxTokens
      completionModelMaxTokens
    }
  }
}
```

## Changelog

NA
2024-07-17 12:38:14 -07:00
Rafał Gajdulewicz
25929d1be9
Integrate Cohere re-ranking API (#63877)
Integrates Cohere re-ranking [API](https://cohere.com/rerank) for
server-side Cody Context ([RFC
969](https://linear.app/sourcegraph/project/v1-of-two-stage-intent-detection-context-retrieval-system-c4f7093e9eab/overview)).
Before this PR, we only supported `identity` ranker (which returned all
items in the input order), which is still the default choice (when
Cohere API key is not provided).

Closes https://linear.app/sourcegraph/issue/AI-134/add-non-poc-ranking

## Test plan

- tested locally, use 
```
"cody.serverSideContext": {
      "reranker": {
        "type": "cohere",
        "apiKey": "TOKEN"
      }
    }
```
to test locally
2024-07-17 19:20:13 +00:00
William Bezuidenhout
658d12ea35
fix(sg): better err msg for when we fail to insert to bigquery (#63873)
Part of: https://github.com/sourcegraph/devx-support/issues/1093

If we get 3 errors in a row trying to write to bigquery ... chances are
we are not going to succeed. So we exit early.

## Test plan
CI
## Changelog
- sg: provide a better error message when we fail to insert into
bigquery
- sg: stop puslishing to bigquery if we get 3 errors in a row
2024-07-17 18:35:56 +02:00
Robert Lin
6d25e2d672
feat/sg/enterprise: add 'sg enterprise set-name' (#63832)
Testing for display-name setting which we recently added, and this is
useful in the interim to set display names on the go for subscriptions
EP already tracks.

note: I don't anticipate doing this for every field we make update-able,
especially since the next step(s) will be updating the UI

## Test plan

```
sg enterprise subscription set-name es_4dae04ba-5f5b-431a-b90b-e8e3dd449181 "robert's test subscription"
```
2024-07-17 09:30:54 -07:00
Felix Kling
d2b6ffa2b3
feat(svelte): Improve small screeen behavior (#63859)
Closes srch-730

This is an initial attempt to improve the web app for small screens.
This commit makes the following changes for small screens:

- Search home page:
  - No more search input overflow
- History button is rendered on same line as other action buttons (saves
some vertical space)
- Search results page:
  - Search input is rendered in the page, not in the header (more space)
- Filters sidebar is hidden by default and can be shown via a `Filters`
button.
  - The filters sidebar opens fullscreen and has a close button
  - The progrss button is smaller due to showing less information
- Repository pages:
- File sidebar is hidden by default. It can be shown via a new button
that is visible in the file headers
  - The file sidebar opens fullscreen and has a close button
- NOTE: Selecting a file currently does not close the file sidebar,
navigation happens in the background
  - Cody sidebar opens fullscreen and has the same close button
- General:
  - Fuzzy finder opens fullscreen and has a larger close button
  - Tabs don't show keyboard shortcuts

I tried to stick to CSS as much as possible but for some things to work
I had to change component structures or rendered elements conditionally.
Specifically when a component was already using `$isViewportMobile` I
usually just rendered elements conditionally.

I extended the `Panel` component to have a special 'mobile' mode, since
I realized I was doing similar changes to the filters, file tree and
cody sidebar.
The cody sidebar is a bit of a special case though because it's not even
rendered by default. So there are some additional steps required to sync
the open state.

Screenshots (iPhone SE, which is one of the smaller phones I guess)

| Situation | Before | After |
|--------|--------|--------|
| Search home |
![2024-07-16_19-13](https://github.com/user-attachments/assets/0072a7b5-07dd-4e2e-bd20-5dd2db53b17d)
|
![2024-07-16_19-16_2](https://github.com/user-attachments/assets/4e9d8af3-e160-4a76-b1e0-158b47520dc9)
|
| Search results |
![2024-07-16_19-14](https://github.com/user-attachments/assets/7555747d-38b4-4db1-a53f-10d6308933b4)
|
![2024-07-16_19-17](https://github.com/user-attachments/assets/6b18db5e-0479-4daa-9342-e88d91a84dbc)
|
| Filters |
![2024-07-16_19-14](https://github.com/user-attachments/assets/7555747d-38b4-4db1-a53f-10d6308933b4)
|
![2024-07-16_19-17_1](https://github.com/user-attachments/assets/c33b5f7e-9723-412c-b682-2806c6e5d3da)
|
| Repo |
![2024-07-16_19-15_1](https://github.com/user-attachments/assets/c90af0ae-8b4e-4c2d-a153-f2bd149a83e5)
|
![2024-07-16_19-17_3](https://github.com/user-attachments/assets/554002c5-8759-4aeb-bcfe-578c339c13de)
|
| File sidebar |
![2024-07-16_19-15_1](https://github.com/user-attachments/assets/c90af0ae-8b4e-4c2d-a153-f2bd149a83e5)
|
![2024-07-16_19-17_4](https://github.com/user-attachments/assets/8baf73f9-0455-4e73-9d7c-032df461871d)
|
| Cody sidebar |
![2024-07-16_19-15_2](https://github.com/user-attachments/assets/8db143bd-ec77-4d4b-8572-23393d056805)
|
![2024-07-16_19-18](https://github.com/user-attachments/assets/b34f8470-1a4d-4682-afb9-5af7ef474191)
|
| Repo search |
![2024-07-16_19-16_1](https://github.com/user-attachments/assets/401fd0b6-8f8f-4b6d-bfcd-99510ee30151)
|
![2024-07-16_19-17_5](https://github.com/user-attachments/assets/57a95fb0-93de-40fa-b5c1-ce3be4a64f6b)
|
| Fuzzy finder |
![2024-07-16_19-16](https://github.com/user-attachments/assets/66a55a9f-95eb-4b7a-b102-67508334ba81)
|
![2024-07-16_19-18_1](https://github.com/user-attachments/assets/9c2859a4-33f4-40af-8028-3e0c6953a579)
|
| Rev picker |
![2024-07-17_00-42](https://github.com/user-attachments/assets/bdc0c993-592f-4975-950b-3b7a13edc810)
|
![2024-07-17_00-41](https://github.com/user-attachments/assets/4f42e7e5-387a-40dc-80aa-109481f0399c)
|

Me rambling about the changes:



https://github.com/user-attachments/assets/670f7764-0ef2-4f1b-bc33-89a86d4b2274


Note that the commits and commit pages already seem to look fine. The
branches, tags and contributors pages are a bit broken due to use of
tables and fixed columns. I can look at those separately.

## Test plan

Manual testing
2024-07-17 16:11:10 +02:00
Michael Bahr
4823c2fc2c
fix: set timeout for web-sveltekit/unit_tests to moderate (#63879)
The unit tests for web-sveltekit have become flaky, and have therefore
been set to run only manually:
https://github.com/sourcegraph/sourcegraph/pull/63874

By running them via `sg ci bazel` I noticed in the waterfall view, that
the tests are taking slightly above one minute
(https://buildkite.com/sourcegraph/sourcegraph/builds/282732/waterfall),
and that previous tests failed because it exceeded a timeout of 1
minute: https://buildkite.com/sourcegraph/sourcegraph/builds/282684

It looks to me like the CI agents are a bit less powerful, and therefore
take longer than our local test runs (which usually don't exceed 10
seconds).

I have not investigated parallelizing the vitest workers, because for
web-sveltekit we currently only have a vite config, but not a vitest
config. More context on that here:
https://github.com/sourcegraph/sourcegraph/pull/60927

## Test plan

CI

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-17 08:01:36 -06:00
Varun Gandhi
f3cc352da7
chore: Mark flaky web-sveltekit tests as manual (#63874) 2024-07-17 18:18:09 +08:00
Rafał Gajdulewicz
66fd1b5172
Add configuration for Intent Detection API (#63871)
Adds site-config configuration for RFC 969 intent detection, making the
Intent Detection API endpoint and token configurable without code
changes. Additionally, adds an option to hit multiple intent detection
backends with the same query.

Previously, URL was hardcoded in code, so if the backend has changed, we
had to redeploy sourcegraph.com.
As we iterate on intent detection, we want to be able to test multiple
models in parallel, so this PR adds a setting for `extra` backends - if
provided, additional .com -> backend requests will be sent, but the
client-initiated request will not wait for those requests.

Closes AI-128.

## Test plan

- tested locally - add 
```
 "cody.serverSideContext": {
      "intentDetectionAPI": {
        "default": {
          "url": "http://35.188.42.13:8000/predict/linearv2"
        },
        "extra": [
          {
            "url": "http://35.188.42.13:8000/predict/linearv2"
          }
        ]
      }
    }
```
to `experimentalFeatures` in dev-private.
2024-07-17 09:47:08 +00:00
Varun Gandhi
8597286c8f
feat: Add experimental feature to control commit graph updates (#63870) 2024-07-17 16:51:18 +08:00
Quinn Slack
2947657755
factor out PatternContainedInput (#63869)
This is an input element that constraints the input to look like a path
component, used for the names of batch changes (and for prompts in the
prompt library in the future).

Also fixes an invalid regexp (it needs to escape `-` because the `'v'`
flag is used; see
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern).

## Test plan

Test against existing batch change create form name input. Try invalid
inputs.
2024-07-17 08:25:09 +00:00
Quinn Slack
05f798a79d
show saved searches in new global navbar (#63868)
This was added to the old global navbar but not the one one by accident
(by me).

## Test plan

Ensure that the new global navbar shows a Saved Searches link.
2024-07-17 01:14:36 -07:00
Varun Gandhi
11817b06d6
docs: Add alternate names and links in GraphQL docs (#63867)
Ideally, we would introduce copies of the old names, deprecate the old
ones, migrate the frontend code, and cut over after a couple of minor
releases.

I don't have time for that now, so just updating the docs a bit for clarity.
2024-07-17 04:48:57 +00:00
Camden Cheek
670ec996dc
Svelte: some unrelated cleanups (#63757)
Just a couple of things I noticed while working on unrelated tasks.

1) Removes the unused `Separator` component, which has been replaced by
the Panel API
2) Makes the sourcegraph mark a proper icon so it can be used via the
`Icon` component like all our other icons.
2024-07-17 02:41:14 +00:00
Camden Cheek
8e6bf0eae3
Svelte: optimize observeIntersection (#63816)
While attempting to use `observeIntersection` with the new references
panel, I was running into performance issues with large lists of
references (the API does not actually paginate yet). When I took a look
at the profile, a good chunk of the time came from finding the nearest
scrolling ancestor, specifically the `overflowY` part, which requires
computing large chunks of the layout.

So this changes the `observeIntersection` action to take an explicit
target container so we don't need to do any searching for a scroll
container. For the example that I was debugging, this reduced the time
it took to render the list ~5x. Additionally, it establishes a cache for
all created `IntersectionObserver`s rather than just the root observer.
2024-07-16 20:13:26 -06:00
Vova Kulikov
290838344e
Upgrade cody web experimental package to 0.2.7 (#63863)
S2 Cody Web is broken at the moment. New client-config handlers fail
with 401 status because we don't send custom headers, this works for gql
queries since they all are POST requests and the browser automatically
sends an Origin header for them and this is enough for our auth
middleware to check cookies, but with client-config which is rest it's
not the case and we should send `X-Requested-Client: Sourcegraph` header
to make our auth middleware to pass this query correctly

Note that this problem doesn't exist in local builds since we proxy all
requests and add `X-Requested-Client: Sourcegraph` in dev server.

See Cody latest build PR for more details
https://github.com/sourcegraph/cody/pull/4898

## Test plan
- CI is passing
2024-07-16 18:43:53 -03:00
Robert Lin
920665ad44
chore/lib/telemetrygateway: fixup Dial helper (#63862)
Makes it a little easier to use

## Test plan

n/a
2024-07-16 20:38:53 +00:00
Robert Lin
61cb0dc807
feat/sg: support correct completions on 'sg start -cmd' (#63861)
`sg run` is supposed to be deprecated in favour of `sg start -cmd`, but
the `sg start` completions don't work with `-cmd` like `sg run` does.

This change updates `sg start` completion to check for the `-cmd` flag,
and if it is provided, offer completions for commands instead of
command_sets_ (the default `sg start` behaviour).

## Test plan

<img width="1023" alt="image"
src="https://github.com/user-attachments/assets/9b887180-f58f-4aef-9dbb-718c71ba15e6">

<img width="1077" alt="image"
src="https://github.com/user-attachments/assets/927b4562-fce1-48c0-a8c5-453bfc60fe35">

## Changelog

- Completions for `sg start -cmd` now offer valid suggestions.
2024-07-16 12:11:11 -07:00
Robert Lin
6212f2585c
chore/sg: clean up help formatting (#63860)
Noticed several `Usage` using newlines, which makes `-h` output pretty
annoying to read as it breaks up the formatting. It tickled me enough to
put a formatting check against it, and update the existing usages that
were incorrect, to use `Description` or `UsageText` instead :-)

## Test plan

CI, `sg -h` is pretty(er) again (but still very long)
2024-07-16 12:01:06 -07:00
Robert Lin
ac5cd73320
chore/enterpriseportal: simplify display_name constraint (#63835)
I've updated the existing values by hand.

## Test plan

n/a
2024-07-16 10:45:17 -07:00
Quinn Slack
1532bcdf6d
misc saved searches followups (#63841)
- Don't show the Tools menu on dotcom for now, since there is only 1
item. Users can still access saved searches in their user menu.
- Fix an issue where non-site admins on dotcom would see an error at
`/saved-searches` until they changed the Owner filter.
- Other minor code cleanups.

## Test plan

Try being a non-site admin and ensure that `/saved-searches` works.
2024-07-16 11:41:37 -06:00
Craig Furman
91864283bc
fix(appliance): do not delete unowned resources (#63826)
The appliance checks owner references, and only deletes (or updates)
resources whose owner references matches the configmap being reconciled.

The current user interface to external databases, is for the admin to
create secrets with a well-known name out of band (e.g. "pgsql-auth")
and then disable the relevant backing services (e.g. pgsql). This commit
fixes a bug in which the appliance would have deleted such secrets,
leaving the admin unable to use external databases.

Discovered while investigating

https://linear.app/sourcegraph/issue/REL-14/ensure-pods-roll-when-referenced-secret-changes,
but does not close it.
2024-07-16 17:18:35 +01:00
Stefan Hengl
c64747b806
chore(worker): disable jobs based on ENVs (#63853)
Relates to https://github.com/sourcegraph/sourcegraph/pull/63686

We check the ENVs added in
https://github.com/sourcegraph/sourcegraph/pull/63686 and disable the
corresponding worker jobs if necessary.

## Test plan
New unit tests
2024-07-16 18:07:22 +02:00
Vova Kulikov
e6bd85e4b7
Upgrade cody web experimental package to 0.2.5 (#63839)
This PR upgrades the cody web experimental package to 0.2.5, in the new
version we fixed
- Telemetry problem with init extension-related events (we don't send
install extension events anymore)
- Most recent updates on LLM availability for enterprise instances 
 
## Test plan
- CI is green
- Manual check on basic Cody Web functionality (highly recommended)
2024-07-16 12:01:03 -03:00
Ólafur Páll Geirsson
ff7a08730b
Revert "Cody: add support for neovim, cody-cli, eclipse, and visualstudio clients (#63854)
This reverts commit 00d812c176.

The motivation to revert this commit is because it wasn't a good fix and
I want to have an easy-to-cherry-pick commit with a good fix (which I
have ready in another branch).

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Green CI.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-16 14:27:16 +00:00
Kevin Chen
59ec1e034e Update flagging.go 2024-07-16 07:15:40 -07:00
Kevin Chen
9d8140ee5f updated error messaging for blocked requests 2024-07-16 07:15:40 -07:00
Erik Seliger
a0a18a60e9
gating: Add individual switches for disabling tools features (#63686)
This PR adds better gating for disabling the code monitors, notebooks,
search jobs and own features.

## Test plan

Ran locally and verified the features are gone when the env var is set.
Ran again without those and they worked.

---------

Co-authored-by: Stefan Hengl <stefan@sourcegraph.com>
2024-07-16 15:45:38 +02:00
Ólafur Páll Geirsson
00d812c176
Cody: add support for neovim, cody-cli, eclipse, and visualstudio clients (#63851)
Fixes CODY-2884

Previously, the server could respond with a 406 error when encountering
clients with the following names: cody-cli, eclipse, and visualstudio.
This error seems to only happen for enterprise clients. This PR fixes
the problem by adding special cases for these clients like we already
have for jetbrains and cody web.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

See updated test case.
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

- Fix HTTP 406 error when using the Neovim Cody plugin with Enterprise
instances
<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-16 13:36:44 +01:00
Ólafur Páll Geirsson
2d76833cc7
Cody: add access token callback pages for CLI, Eclipse and VS (#63849)
Fixes CODY-2661

Previously, only the JetBrains and Neovim Cody plugins had dedicated
pages to authorize access token redirects to a localhost port. Other
clients like the Cody CLI and Eclipse plugin reused the JetBrains page,
which technically works but is problematic because the UI says the user
is authorizing "JetBrains" when in reality they're authorizing other
clients. This PR fixes the problem by adding dedicated pages for the
Cody CLI, Eclipse plugin and Visual Studio extension.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Didn't test this locally because it takes me a long time to setup Docker
access. The diff is small and should be low-risk to merge. I manually
searched for 'JETBRAINS' in this directory and confirmed there are no
remaining special cases for JetBrains.

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-16 10:56:17 +01:00
William Bezuidenhout
07e59761d2
pr-auditor: use pr-auditor from devx-service (#63847)
Updates PR-auditor to use the PR-auditor from the devx-service

## Test plan
Once merged, this
[PR](https://github.com/sourcegraph/sourcegraph/pull/63846) should fail
2024-07-16 11:10:36 +02:00
Felix Kling
5a0d078fae
chore(svelte): Disable tests which time out (#63844)
These two tests seem to time out regularly (e.g.

https://buildkite.com/sourcegraph/sourcegraph/builds/282453#0190b9e2-2f71-4876-a84f-c40783e906c8)


## Test plan

CI
2024-07-16 10:02:06 +02:00
Stefan Hengl
ae0f2dd5ef
fix(search_jobs): remove trailing * from URL (#63821)
Navigating to the Search Jobs overview page now goes to `/search-jobs`
instead of `/search-jobs/*`

Test plan:
manual testing
2024-07-16 09:58:13 +02:00
Felix Kling
902b89851a
chore(svelte): Refactor repo loaders (#63828)
This commit is in preparation for other work. It refactors how we work
with resolved repository and resolved revision information.

The idea was that the top level repo loader should try to resolve the
repository information and error if that wasn't possible. Not being able
to resolve the revision was accepted, hence this check:

```js
// still render the main repo navigation and header
if (!isRevisionNotFoundErrorLike(repoError)) {
  error(400, asError(repoError))
}
```

However the way it was implemented meant that we wouldn't pass any
resolved repository information to the sub-pages/layouts when the
revision couldn't be resolved, which seems wrong.

With these changes, the top level repo loader now provides a
`resolvedRepository` object (where `commit`/`changelist` might be unset)
and the `(validrev)` loader creates the `resolvedRevision` object, just
how its sub-pages/layouts expect.

And instead of returning error objects from `resolveRepoRevision` and
checking them in the loader we throw errors/redirects directly in that
function. IMO that makes the whole flow easier to understand.

## Test plan

Manual testing, CI integration tests
2024-07-16 05:45:48 +00:00
Felix Kling
23616fa5c0
chore(svelte): Refactor infinity query implementation (#63824)
In preparation for other work, this commit substantially refactors the
"infinity query" store implementation. The internals have been changed
completely which allows us to simplify its public API.

- Simpler configuration, especially merging previous and next results.
- Restoration support. So far pages/components had to implement
restoring the state of an infinity store on their own. Now the
restoration strategy is part of the configuration. Pages/components only
have to get an opaque snapshot via `store.capture()` and restore it via
`store.restore(snapshot)`.
- More predictable state. It wasn't always obvious if the store content
stale data e.g. during restoring data. Now `data` will only be set when
the data is 'fresh'.
- Smarter 'incremental restoration' strategy. This strategy makes
multiple requests to restore the previous state. It makes multiple
requests because normally requests are cached and there this is fast.
When the data is not cached though there is a noticable delay due to
waterfall requests. Now we use a simple heuristic to determine whether
or not GraqhQL data might be cached. If not we make a single request to
restore the state.

For review I suggest to turn whitespace changes off.

## Test plan

Manual testing, unit tests.
2024-07-16 06:51:36 +02:00
Erik Seliger
6a7b3bb102
webhooks: Deterministically match webhook events to repos (#63668)
Previously, we would attempt to recreate the clone URL of a repo based
on event data. This is a lossy matching, and can cause events to get
rejected, although we have the repo cloned.

This PR changes the matching to instead use the external ID of the repo,
which we already store in the repo table in a separate column.

Closes SRC-40

Test plan:

Tests still pass, set up webhooks locally and they still matched (but
only tried GitHub).
2024-07-16 06:50:13 +02:00
Quinn Slack
7ba706e65d
various improvements to saved searches (#63539)
- Remove long-deprecated and long-ineffective notifications for saved
searches (removed in
de8ae5ee28
2.5 years ago). Note that code monitors were the replacement for saved
searches and work great.
- Clean up UI.
- Make the UI global instead of in the user/org area.
- Convert React class components to function components.
- Add default `patterntype:` because it's required.
- Use `useQuery` and `useMutation` instead of `requestGraphQL`.
- Use a single namespace `owner` GraphQL arg instead of separating out
`userID` and `orgID`.
- Clean up GraphQL resolver code and factor out common auth checking.
- Support transferring ownership of saved searches among owners (the
user's own user account and the orgs they're a member of).

(I know this is not in Svelte.)

SECURITY: There is one substantive change. Site admins may now view any
user's and any org's saved searches. This is so that they can audit and
delete them if needed.


![image](https://github.com/sourcegraph/sourcegraph/assets/1976/7ba22c1c-b92e-4089-836b-135a503c96a0)

![image](https://github.com/sourcegraph/sourcegraph/assets/1976/a1f2f43d-f681-4ec9-b2a1-8273707b34ee)

![image](https://github.com/sourcegraph/sourcegraph/assets/1976/5ee1164f-ed2e-4144-9aca-db61fa7c20f4)

![image](https://github.com/sourcegraph/sourcegraph/assets/1976/d631529e-6c0d-49c6-9be1-33a7ff53ed97)


## Test plan

Try creating, updating, and deleting saved searches, and transferring
ownership of them.

## Changelog

- Improved the saved searches feature, which lets you save search
queries to easily reuse them later and share them with other people in
an organization.
- Added the ability to transfer ownership of a saved search to a user's
organizations or from an organization to a user's account.
- Removed a long-deprecated and ineffective settings
`search.savedQueries` field. You can manage saved searches in a user's
or organization's profile area (e.g., at `/user/searches`).
2024-07-15 20:12:34 +00:00
Quinn Slack
e73efbe1de
make pagination hooks store filter & query params in URL, not just pagination params (#63744)
This is a refactor with a few incidental user-facing changes (eg not
showing a sometimes-incorrect total count in the UI).

---

Make `usePageSwitcherPagination` and `useShowMorePaginationUrl` support
storing filter and query params, not just pagination params, in the URL.
This is commonly desired behavior, and there are many ways we do it
across the codebase. This attempts to standardize how it's done. It does
not update all places this is done to standardize them yet.

Previously, you could use the `options: { useURL: true}` arg to
`usePageSwitcherPagination` and `useShowMorePaginationUrl`. This was not
good because it only updated the pagination URL querystring params and
not the filter params. Some places had a manual way to update the filter
params, but it was incorrect (reloading the page would not get you back
to the same view state) and had a lot of duplicated code. There was
actually no way to have everything (filters and pagination params)
updated in the URL all together, except using the deprecated
`<FilteredConnection>`.

Now, callers that want the URL to be updated with the connection state
(including pagination *and* filters) do:

```typescript
const connectionState = useUrlSearchParamsForConnectionState(filters)
const { ... } = usePageSwitcherPagination({ query: ..., state: connectionState}) // or useShowMorePaginationUrl
```

Callers that do not want the connection state to be reflected in the URL
can just not pass any `state:` value.

This PR also has some other refactors:

- remove `<ConnectionSummary first>` that was used in an erroneous
calculation. It was only used as a hack to determine the `totalCount` of
the connection. This is usually returned in the connection result itself
and that is the only value that should be used.
- remove `?visible=N` param from some connection pages, just use
`?first=N`. This was intended to make it so that if you reloaded or
navigated directly to a page that had a list, subsequently fetching the
next page would only get `pageSize` additional records (eg 20), not
`first` (which is however many records were already showing) for
batch-based navigation. This is not worth the additional complexity that
`?visible=` introduces, and is not clearly desirable even.
- 2 other misc. ones that do not affect user-facing behavior (see commit
messages)


## Test plan

Visit the site admin repositories and packages pages. Ensure all filter
options work and pagination works.
2024-07-15 19:17:59 +00:00
Jacob Pleiness
b71c986c77
chore(appliance): Stub out react UI expected URIs and JSON API (#63741)
This PR stubs out the URI needed for the React UI to interface with the
appliance, as well as removed the previously implemented UI and
components of the React UI that were only around for a demo.

A number of helper and safety methods have also been added for
interfacing with JSON reads/writes and handling common errors.

While the HTTP handlers are still only stubs, this PR was growing in
size so I decided to cut it here and break apart the rest in upcoming
PRs. React UI is able to parse status and auth correctly at this time.

<!-- PR description tips:
https://www.notion.so/sourcegraph/Write-a-good-pull-request-description-610a7fd3e613496eb76f450db5a49b6e
-->

## Test plan

Unit tests

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-15 14:48:38 -04:00
Robert Lin
795f0bbc72
feat/enterpriseportal: db layer for subscription licenses (#63792)
Implements CRUD on the new licenses DB. I had to make significant
changes from the initial setup after spending more time working on this.

There's lots of schema changes but that's okay, as we have no data yet.

As in the RPC design, this is intended to accommodate new "types" of
licensing in the future, and so the DB is structured as such as well.
There's also feedback that context around license management events is
very useful - this is encoded in the conditions table, and can be
extended to include more types of conditions in the future.

Part of https://linear.app/sourcegraph/issue/CORE-158
Part of https://linear.app/sourcegraph/issue/CORE-100

## Test plan

Integration tests

Locally, running `sg run enterprise-portal` indicates migrations proceed
as expected
2024-07-15 11:47:51 -07:00
Robert Lin
879646a20e
feat/sg/msp: helpful error on cloudsqlproxy port conflict (#63830)
Ported from https://github.com/sourcegraph/controller/pull/1622 :) 

## Test plan

n/a
2024-07-15 11:32:37 -07:00
Robert Lin
2b3333aead
feat/lib/telemetrygateway: expose simple Dial (#63810)
For simple, MVP integrations with Telemetry Gateway, and also as a
reference. See example - this can be consumed with:

```go
import telemetrygatewayv1 "github.com/sourcegraph/sourcegraph/lib/telemetrygateway/v1"
```

## Test plan

n/a
2024-07-15 10:45:10 -07:00
Robert Lin
3250df9e1b
chore/telemetrygateway: gracefully handle sams introspectToken cancelation (#63809)
As titled, not much to action about these.

## Test plan

n/a
2024-07-15 10:45:00 -07:00
Chris Smith
8d4e5b52f4
Several fixes around merging modelconfig, and the current Cody Gateway data (#63814)
While testing the modelconfig system working end-to-end with the data
coming from the site configuration, I ran into a handful of minor
issues.

They are all kinda subtle so I'll just leave comments to explain the
what and why.

## Test plan

Added new unit tests.

## Changelog

NA
2024-07-15 17:14:28 +00:00
Rafał Gajdulewicz
c1efb92196
RFC 969 API boilerplate (#63789)
This PR adds experimental endpoints implementing for context ranking and
storage, as required by RFC 969.
Also removes the deprecated and unused `getCodyIntent` query (we have
`chatIntent`).

## Test plan

- tested locally, not integrated with any clients
2024-07-15 16:25:56 +00:00
Namit Chandwani
2b07b4aa1d
fix: make invalid token error message visible while adding external services (#60876)
## Linked Issues
- Closes https://github.com/sourcegraph/sourcegraph/issues/35027


## Motivation and Context:
<!--- Why is this change required? What problem does it solve? --> 
- To improve the UX by displaying the invalid token error message on the
UI to the users while adding a code host connection

## Existing Issue Root Cause:
- After the submit button is clicked while adding a code host
connection, the existing code navigates to the
`/site-admin/external-services/${data.addExternalService.id}` page (the
page which displays information of the newly added code host connection)
before the error message could even be displayed on the current page

## Changes Made:
<!--- Please include a summary of the change and which issue is fixed.
Please also include relevant motivation and context. List any
dependencies that are required for this change. -->
- Modified the onSubmit function (the one which is called when the
submit button is clicked on the code host connection addition page) to
only navigate to the
`/site-admin/external-services/${data.addExternalService.id}` page
(newly added code host information page) only if no error/warning is
returned from the gRPC call which validates the token of the code host
added


## Type of change:

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Refactoring (altering code without changing its external
behaviour)
- [ ] Documentation change
- [ ] Other


## Checklist:

- [x] Development completed
- [x] Comments added to code (wherever necessary)
- [x] Documentation updated (if applicable)
- [x] Tested changes locally


## Follow-up tasks (if any):

- None

## Test Plan
<!--- Please describe the tests that you ran to verify your changes.
Provide instructions so we can reproduce. -->

- Had setup the codebase locally and tested the entire flow locally
end-to-end
- Screen recording which shows the invalid token error message on the UI
in the code host connection addition flow:
 

https://github.com/sourcegraph/sourcegraph/assets/51479159/1857f32d-56a6-42c1-af88-ea3c9edc46a5


## Additional Comments
- Please let me know if any further changes are required elsewhere
2024-07-15 15:01:07 +01:00
Stefan Hengl
3a20c00693
chore(search_jobs): remove label "admin" from contact card (#63823)
This removes the label "admin" next to the user's name and email
address. The label has no relevance for Search Jobs.

Test plan:
manual testing

**before**
<img width="1177" alt="Screenshot 2024-07-15 at 12 06 05"
src="https://github.com/user-attachments/assets/df1581b1-837a-4aaa-bc36-b5fa45e59d1a">

**after**
<img width="1185" alt="Screenshot 2024-07-15 at 12 00 11"
src="https://github.com/user-attachments/assets/fb3222dd-5dd6-429d-a6fe-519812755cd4">
2024-07-15 13:46:06 +02:00
Varun Gandhi
f6ef5919e6
chore: Use Option type and rename API (#63820) 2024-07-15 19:31:37 +08:00
William Bezuidenhout
d7db73f0cd
fix(nix/p4-fusion): update p4-fusion helix-api hashes (#63805)
Failed run here
https://github.com/sourcegraph/p4-fusion/actions/runs/9890851838/job/27320002177.

I tried looking at the sha256 hashes here -
https://filehost.perforce.com/perforce/r22.2/bin.macosx12arm64/SHA256SUMS

But there is no clear way to convert to the nix format. There is `nix
hash convert` but it's not available in my nix version.

So ... I took the values reported in the workflow and used them in this
PR

## Test plan
CI
## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-15 10:20:33 +02:00
Julie Tibshirani
cf05a9b2a5
Structural search: fix precise lang filtering (#63791)
The feature `search-content-based-lang-detection` was never implemented
for structural search. This PR fills in the missing pieces.

Fixes #61714
Relates to
https://linear.app/sourcegraph/project/make-precise-lang-filtering-default-4f06cfa28567

## Test plan

Two new unit tests checking that the lang filters are now correctly
passed to Zoekt.
2024-07-15 09:20:21 +02:00
Hitesh Sagtani
660d6866b5
change model identifier for finetuned deepseek model (#63817)
## Context
1. Change model identifier for deepseek-coder-v2 model for fine-tuned
models.

## Test plan
```
curl -vS -X POST http://localhost:9992/v1/completions/fireworks -H 'Authorization: bearer <SGD_TOKEN>' -d '{"stream":false,"max_tokens":50, "model": "fim-lang-specific-model-deepseek-stack-trained", "stop_sequences": ["\n\n"], "prompt": "const value = ", "stream":false, "languageId": "python"}' -H 'X-sourcegraph-feature: code_completions'
```

```
curl -vS -X POST http://localhost:9992/v1/completions/fireworks -H 'Authorization: bearer <SGD_TOKEN>' -d '{"stream":false,"max_tokens":50, "model": "fim-lang-specific-model-deepseek-logs-trained", "stop_sequences": ["\n\n"], "prompt": "const value = ", "stream":false, "languageId": "python"}' -H 'X-sourcegraph-feature: code_completions'
```
2024-07-14 13:47:50 +00:00
Bolaji Olajide
1c40c9e5bc
fix(batches): the baseURL for github instance is now updated when creating a GitHub app (#63803)
Closes SRCH-723

The baseURL for GitHub apps defaults to `https://github.com` when no
`externalServiceURL`, we somehow missed this during our testing.

![CleanShot 2024-07-12 at 11 57
00@2x](https://github.com/user-attachments/assets/99b68a11-de38-4a2d-8c4c-3219f0c9abf7)


## Test plan

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

Manual testing with the GHE instance.

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-13 22:43:24 +01:00
Julie Tibshirani
aaee245a31
fix(svelte): respect default pattern type in toggles (#63795)
In Sveltekit, we respect the setting `search.defaultPatternType` for the
initial search, but if you set then unset the regexp toggle, it always
reverts to `keyword`. Now we revert back to the default when a toggle is
unset.

This is important because some customers have disabled keyword search,
and for 5.5 we've directed them to use `search.defaultPatternType:
standard`.

## Test plan

Manually tested search + toggles with following config:
* No settings
* `search.defaultPatternType: standard`, `keyword`, and `regexp`
2024-07-12 14:22:24 -07:00
Chris Smith
02c07df176
feat/cody: Refactor completions API to use new modelconfig (support more models) (#63797)
This PR if what the past dozen or so
[cleanup](https://github.com/sourcegraph/sourcegraph/pull/63359),
[refactoring](https://github.com/sourcegraph/sourcegraph/pull/63731),
and [test](https://github.com/sourcegraph/sourcegraph/pull/63761) PRs
were all about: using the new `modelconfig` system for the completion
APIs.

This will enable users to:

- Use the new site config schema for specifying LLM configuration, added
in https://github.com/sourcegraph/sourcegraph/pull/63654. Sourcegraph
admins who use these new site config options will be able to support
many more LLM models and providers than is possible using the older
"completions" site config.
- For Cody Enterprise users, we no longer ignore the
`CodyCompletionRequest.Model` field. And now support users specifying
any LLM model (provided it is "supported" by the Sourcegraph instance).

Beyond those two things, everything should continue to work like before.
With any existing "completions" configuration data being converted into
the `modelconfig` system (see
https://github.com/sourcegraph/sourcegraph/pull/63533).

## Overview

In order to understand how this all fits together, I'd suggest reviewing
this PR commit-by-commit.

### [Update internal/completions to use
modelconfig](e6b7eb171e)

The first change was to update the code we use to serve LLM completions.
(Various implementations of the `types.CompletionsProvider` interface.)

The key changes here were as follows:

1. Update the `CompletionRequest` type to include the `ModelConfigInfo`
field (to make the new Provider and Model-specific configuration data
available.)
2. Rename the `CompletionRequest.Model` field to
`CompletionRequest.RequestedModel`. (But with a JSON annotation to
maintain compatibility with existing callers.) This is to catch any bugs
related to using the field directly, since that is now almost guaranteed
to be a mistake. (See below.)

With these changes, all of the `CompletionProvider`s were updated to
reflect these changes.

- Any situation where we used the
`CompletionRequest.Parameters.RequestedModel` should now refer to
`CompletionRequest.ModelConfigInfo.Model.ModelName`. The "model name"
being the thing that should be passed to the API provider, e.g.
`gpt-3.5-turbo`.
- In some situations (`azureopenai`) we needed to rely on the Model ID
as a more human-friendly identifier. This isn't 100% accurate, but will
match the behavior we have today. A long doc comment calls out the
details of what is wrong with that.
- In other situations (`awsbedrock`, `azureopenai`) we read the new
`modelconfig` data to configure the API provider (e.g.
`Azure.UseDeprecatedAPI`), or surface model-specific metadata (e.g. AWS
Provisioned Throughput ARNs). While the code is a little clunky to avoid
larger refactoring, this is the heart and soul of how we will be writing
new completion providers in the future. That is, taking specific
configuration bags with whatever data that is required.

### [Fix bugs in
modelconfig](75a51d8cb5)

While we had lots of tests for converting the existing "completions"
site config data into the `modelconfig.ModelConfiguration` structure,
there were a couple of subtle bugs that I found while testing the larger
change.

The updated unit tests and comments should make that clear.

### [Update frontend/internal/httpapi/completions to use
modelconfig](084793e08f)

The final step was to update the HTTP endpoints that serve the
completion requests. There weren't any logic changes here, just
refactoring how we lookup the required data. (e.g. converting the user's
requested model into an actual model found in the site configuration.)

We support Cody clients sending either "legacy mrefs" of the form
`provider/model` like before, or the newer mref
`provider::apiversion::model`. Although it will likely be a while before
Cody clients are updated to only use the newer-style model references.

The existing unit tests for the competitions APIs just worked, which was
the plan. But for the few changes that were required I've added comments
to explain the situation.

### [Fix: Support requesting models just by their
ID](99715feba6)

> ... We support Cody clients sending either "legacy mrefs" of the form
`provider/model` like before ...

Yeah, so apparently I lied 😅 . After doing more testing, the extension
_also_ sends requests where the requested model is just `"model"`.
(Without the provider prefix.)

So that now works too. And we just blindly match "gtp-3.5-turbo" to the
first mref with the matching model ID, such as
"anthropic::unknown::gtp-3.5-turbo".

## Test plan

Existing unit tests pass, added a few tests. And manually tested my Sg
instance configured to act as both "dotcom" mode and a prototypical Cody
Enterprise instance.

## Changelog

Update the Cody APIs for chat or code completions to use the "new style"
model configuration. This allows for great flexibility in configuring
LLM providers and exposing new models, but also allows Cody Enterprise
users to select different models for chats.

This will warrant a longer, more detailed changelog entry for the patch
release next week. As this unlocks many other exciting features.
2024-07-12 12:15:31 -07:00
Vova Kulikov
fbb0a1fec1
Move Cody Web to beta (#63806)
Closes
https://linear.app/sourcegraph/issue/CODY-2847/change-experimental-labels-to-beta

## Test plan
- Check that cody web page and cody web side panel have beta badges
2024-07-12 13:37:10 -03:00
Camden Cheek
1218b49d41
Svelte: add more general shrinkable path (#63770)
This adds two new components for the common situation of needing to
display a styled path.

- `DisplayPath` handles splitting, coloring, spacing, slotting in a file
icon, adding a copy button, and ensuring that no spaces get introduced
when copying the path manually
- `ShrinkablePath` is built on top of `DisplayPath` and adds the ability
to collapse path elements into a dropdown menu

These are used in three places:
- The file header. There should be no change in behavior except maybe a
simplified DOM. This makes use of the "Shrinkable" version of the
component.
- The file search result header. This required carefully ensuring that
the text content of the node is exactly equal to the path so that the
character offsets are correct.
- The file popover, where it is used for both the repo name (unlinkified
version) and the file name (linkified version).

Fixes SRCH-718
Fixes SRCH-690
2024-07-12 10:36:37 -06:00
Julie Tibshirani
85686e40e1
Search: make 'exclude tests' more general (#63762)
The "Exclude" options in the filter panels are very useful, but many are specific to Go. This change generalizes them so they apply in many more cases:
* All files with suffix `_test` plus extension (covers Go, Python, some Ruby, C++, C, more)
* All files with suffix `.test` plus extension (covers Javascript, some Ruby)
* Ruby specs
* Third party folders (common general naming pattern)

Relates to SPLF-70
2024-07-12 09:30:52 -07:00
Felix Kling
0102ac9b57
fix(svelte): Ctrl+backspace in fuzzy finder (#63804)
We register ctrl+backspace to go to the repository root, but that should
not trigger when an input field, such as the fuzzy finder, is focused.

Fixes srch-681

## Test plan

Manual testing.
2024-07-12 16:54:13 +02:00
Namit Chandwani
528d98e0e3
feat: show current email during password reset and auto-populate text-box after successful completion (#59645)
## Linked Issues
- Closes https://github.com/sourcegraph/sourcegraph/issues/38348


## Motivation and Context:
<!--- Why is this change required? What problem does it solve? --> 
- Improves the UX of the password reset flow

## Changes Made:
<!--- Please include a summary of the change and which issue is fixed.
Please also include relevant motivation and context. List any
dependencies that are required for this change. -->
- Made changes to the following 2 flows:
	- On the new password entry screen:
- Added a text which displays the email of the account for which the
password change request has been raised
- Added a back button to allow the users to go back to the previous
email entry screen if the account they want to reset the password for is
different
- On the sign-in screen which comes after successful password reset
request completion:
- Made changes to auto-populate the email text-box with the email linked
to the account on which the password reset request was completed
recently


## Type of change:

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Refactoring (altering code without changing its external
behaviour)
- [ ] Documentation change
- [ ] Other


## Checklist:

- [x] Development completed
- [ ] Comments added to code (wherever necessary)
- [ ] Documentation updated (if applicable)
- [x] Tested changes locally


## Follow-up tasks (if any):

- None

## Test Plan
<!--- Please describe the tests that you ran to verify your changes.
Provide instructions so we can reproduce. -->

- Setup the codebase locally along with configuring a custom SMTP to
enable the email delivery functionality with the help of this
documentation:
https://docs.sourcegraph.com/admin/config/email#configuring-sourcegraph-to-send-email-using-another-provider

 - Tested the entire flow locally end-to-end.
- Screen recording of the password reset screen where the current email
ID is added along with a back button:
	 	

https://github.com/sourcegraph/sourcegraph/assets/51479159/a79fc338-ace0-4281-86d2-de7cc68eae20
	 
- Screen recording of the sign-in screen after password reset is
successfully done where the email ID is auto-populated in the text-box:
	 	

https://github.com/sourcegraph/sourcegraph/assets/51479159/be7db65d-9421-4621-a1e9-a04a546b9757



    
## Additional Comments
- Please let me know if I need to make any further design changes from
the frontend side or any API contract related changes from the backend
side

---------

Co-authored-by: Vincent <evict@users.noreply.github.com>
Co-authored-by: Shivasurya <s.shivasurya@gmail.com>
2024-07-12 15:45:35 +01:00
Erik Seliger
46837deb91
webhooks: Polish UI components (#63664)
This PR overhauls the UI a bunch to make it look more in line with other
pages, and fixes various smaller papercuts and bugs.

Closes SRC-377

Test plan:

Added storybooks and made sure existing ones still look good, created,
updated, deleted various webhooks locally.
2024-07-12 16:02:46 +02:00
William Bezuidenhout
55f5dc7d91
fix(sg): do not try to publish analytics when it is disabled (#63800)
The background publisher was started regardless if analytics was
disabled or not. This PR makes it so that we only publish analytics if
it is enabled.

To make it work and not duplicate the disabled analytics check, I moved
the usershell + background context creation to happen earlier.

## Test plan
CI and tested locally

## Changelog
* sg - only start the analytics background publisher when analytics are
enabled

---------

Co-authored-by: Jean-Hadrien Chabran <jh@chabran.fr>
2024-07-12 12:45:08 +02:00
Varun Gandhi
ec7f9ab90b
chore: Bump autoindexing image SHAs (#63801) 2024-07-12 09:07:54 +00:00
Stefan Hengl
b77809cf9a
chore(search): update search API call sites to set the version explicitly (#63782)
I went through all call sites of the 3 search APIs (Stream API, GQL API,
SearchClient (internal)) and made sure that the query syntax version is
set to "V3".

Why?

Without this change, a new default search syntax version might have
caused a change in behavior for some of the call sites.

## Test plan
- No functional change, so relying mostly on CI
- The codeintel GQL queries set the patternType explicitly, so this
change is a NOP.

I tested manually
- search based code intel sends GQL requests with version "V3"
- repo badge still works
- compute GQL returns results
2024-07-12 10:01:47 +02:00
Felix Kling
1cf0ad8098
chore(svelte): Commit/diff style and behavior tweaks (#63785)
A couple of tweaks to the commit / diff view:

- Linking both file paths in the header for renamed files
- Collapse renamed file diffs without changes by default
- Move "no changes" out of `FileDiffHunks` to not render a border around
the test.
- Add description for binary files
- Adjust line height and font size to match what we use in the file view
- Added the `visibly-hidden` utility class to render content for a11y
purposes (I didn't test the changes I made with a screenreader though)

Contributes to SRCH-523


## Test plan

Manual testing
2024-07-11 18:44:04 +00:00
Robert Lin
ffa873f3ad
fix/alertmanager: downgrade prometheus/common to fix generated config (#63790)
The OTEL upgrade https://github.com/sourcegraph/sourcegraph/pull/63171
bumps the `prometheus/common` package too far via transitive deps,
causing us to generate configuration for alertmanager that altertmanager
doesn't accept, at least until the alertmanager project cuts a new
release with a newer version of `promethues/common`.

For now we forcibly downgrade with a replace. Everything still builds,
so we should be good to go.

## Test plan
`sg start` and `sg run prometheus`. On `main`, editing
`observability.alerts` will cause Alertmanager to refuse to accept the
generated configuration. With this patch, all is well it seems - config
changes go through as expected. This is a similar test plan for
https://github.com/sourcegraph/sourcegraph/pull/63329

## Changelog

- Fix Prometheus Alertmanager configuration failing to apply
`observability.alerts` from site config
2024-07-11 18:03:54 +00:00
Erik Seliger
197ad80cff
gateway: Don't panic because of duplicate env var registration (#63787)
`REDIS_ENDPOINT` is now registered by gateway, but it is also registered
in `internal/redispool` as the fallback for when the other values are
not set.

The real fix would be to not have env vars in that package, and instead
each service creates one instance of each of those two in their `cmd/`,
but that's a lot of work so short-term fixing it by reading the fallback
using os.Getenv.

Test plan:

`sg run cody-gateway` doesn't panic.

---------

Co-authored-by: Jean-Hadrien Chabran <jh@chabran.fr>
2024-07-11 17:58:28 +00:00
Craig Furman
a20b0650b4
feat(appliance): self-update (#63780)
**chore(appliance): extract constant for configmap name**

To the reconciler, this is just a value, but to higher-level packages
like appliance, there is a single configmap that is an entity. Let's
make sure all high-level orchestration packages can reference our name
for it. This could itself be extracted to injected config if there was a
motivation for it.



**chore(appliance): extract NewRandomNamespace() in k8senvtest**

From reconciler tests, so that we can reuse it in self-update tests.



**feat(appliance): self-update**

Add a worker thread to the appliance that periodically polls release
registry for newer versions, and updates its own Kubernetes deployment.

If the APPLIANCE_DEPLOYMENT_NAME environment variable is not set, this
feature is disabled. This PR will be accompanied by one to the
appliance's helm chart to add this variable by default.



**fix(appliance): only self-update 2 minor versions above deployed SG**




**chore(appliance): self-update integration test extra case**

Check that self-update doesn't run when SG is not yet deployed.

https://linear.app/sourcegraph/issue/REL-212/appliance-can-self-upgrade
2024-07-11 17:59:39 +01:00
William Bezuidenhout
ccae82a85b
fix(sg): return different error types depending on secret failure (#63779)
If we failed getting a secret via a tool - we return CommandErr which
contains SecretErr
If we failed getting a secret via Google - we return GoogleSecretErr
which contains SecretErr

Depending on the error we get while trying to persist Analytics we
suggest different fixes the user can try.

Below is how it looks when we get a GoogleSecretErr

![Screenshot 2024-07-11 at 11 11
40](https://github.com/sourcegraph/sourcegraph/assets/1001709/12479561-c1f5-4de7-b00e-01a1fbb49ece)

## Test plan
Tested locally
<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->
2024-07-11 18:26:14 +02:00
Julie Tibshirani
004eb0fd83
Context: return lines around symbol match (#63773)
This PR fixes an important bug in #62976, where we didn't properly map the
symbol line match to the return type. Instead, we accidentally treated symbol
matches like file matches and returned the start of the file.

## Test plan

Add new unit test for symbol match conversion. Extensive manual testing.
2024-07-11 08:47:03 -07:00
Jean-Hadrien Chabran
ec34a909bc
chore(config): clarify env var already registered panic (#63784)
When `internal/env/env.Get` detects a difference in between already
registered descriptions, it panics (good). But the error message doesn't
tell you what's the difference and you're left out to put a few prints
for yourself in the code to try to understand what's wrong.

See also: https://github.com/sourcegraph/sourcegraph/pull/63786

Before:

<img width="1109" alt="image"
src="https://github.com/sourcegraph/sourcegraph/assets/10151/56b2d65c-ef87-4134-bfc0-67248aa48350">

After: 

![CleanShot 2024-07-11 at 15 26
13@2x](https://github.com/sourcegraph/sourcegraph/assets/10151/406bca90-2b87-481d-aad3-6550afaca29f)


## Test plan

CI + local run 

## Changelog

- When conflicting env var are detected, print the two to ease
debugging.
2024-07-11 13:59:29 +00:00
Felix Kling
46794b5677
fix(svelte): Show correct line numbers in unified diff (#63778)
Fixes srch-717

This commit fixes the line numbers for unified diff views, which are
used on the commit page and for inline diffs.

## Test plan

Manual testing.

| Before | After |
|--------|--------|
|
![2024-07-11_10-40](https://github.com/sourcegraph/sourcegraph/assets/179026/170ac815-d038-4239-80fe-7d35cecfa832)
|
![2024-07-11_10-38](https://github.com/sourcegraph/sourcegraph/assets/179026/3606cb34-ad87-43bf-9664-414bf9250fa4)
|
2024-07-11 13:19:35 +02:00
Petri-Johan Last
1e8a1bb52a
Update comment and decode bytes instead (#63754) 2024-07-11 09:40:51 +02:00
Camden Cheek
c000c81313
Usages API: implement surroundingContent (#63730)
Instead of fetching the file for every node, this passes in a
request-scoped cache to minimize the number of gitserver roundtrips, but
does no fetching if `surroundingContent` is not requested by the caller.
2024-07-11 07:37:59 +00:00
Felix Kling
7761f37e72
chore(svelte): Clean up dependencies (#63777)
This commit removes files/dependencies that we are not using (anymore).
In the case of `@sourcegraph/wildcard` we never want to import
dependencies from it, but have done so accidentally in the past. I hope
that we can prevent this by removing it from dependencies (and we don't
need anyway).

## Test plan

`pnpm build` and CI
2024-07-11 09:31:46 +02:00
Varun Gandhi
be0cd097f5
Correctly re-map source ranges in new SCIP-based APIs (#63630)
This PR fixes the following:
- Handles source range translation in the occurrences API
  (Fixes https://linear.app/sourcegraph/issue/GRAPH-705)
- Handles range translation when comparing with document occurrences in
   search-based and syntactic usagesForSymbol implementations

Throwing this PR up in its current state as I think adding the bulk
conversion
API will be a somewhat complex task, so we should split them into
separate
PRs anyways, and I don't have time to continue working on this right
now.

Some design notes:
- We want to avoid passing around full CompletedUpload and RequestState
objects,
which is why I chose to create a smaller UploadSummary type and decided
to pass
around GitTreeTranslator as that is the minimal thing we need to handle
range re-mapping.
- Yes, this PR increases the surface of the UploadLike type, but I think
it's still quite manageable.

## Test plan

manual testing, existing tests on gittreetranslator
---------

Co-authored-by: Christoph Hegemann <christoph.hegemann@sourcegraph.com>
2024-07-11 06:55:46 +00:00
Varun Gandhi
c645cdc0dd
chore(codeintel): Replace 'dumps' terminology in comments (#63775) 2024-07-11 06:22:10 +00:00
Robert Lin
a07a1b9ed0
chore/sg: remove 'sg telemetry' and related docs (#63763)
Removes the `sg telemetry` command that pertains to the legacy V1
exporter that is specific to Cloud instances.

I got asked about this recently, and especially with the new `sg
analytics` for usage of the `sg` CLI, this has the potential to be
pretty confusing.

Part of https://linear.app/sourcegraph/issue/CORE-104

## Test plan

n/a

## Changelog

- `sg`: the deprecated `sg telemetry` command for allowlisting export of
V1 telemetry from Cloud instances has been removed. Use telemetry V2
instead.
2024-07-10 17:25:04 -07:00
Warren Gifford
cb19d6f0a9
release/bug: generate a new stitched migration graph (#63764)
This will correct6 upgrade path for mvu plan creation

## Test plan

CI test

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->

## Changelog

<!-- OPTIONAL; info at
https://www.notion.so/sourcegraph/Writing-a-changelog-entry-dd997f411d524caabf0d8d38a24a878c
-->

---------

Co-authored-by: Release Bot <107104610+sourcegraph-release-bot@users.noreply.github.com>
Co-authored-by: Jean-Hadrien Chabran <jean-hadrien.chabran@sourcegraph.com>
Co-authored-by: Anish Lakhwara <anish+git@lakhwara.com>
Co-authored-by: Jean-Hadrien Chabran <jh@chabran.fr>
Co-authored-by: Anish Lakhwara <anish+github@lakhwara.com>
2024-07-10 14:49:18 -07:00
Chris Smith
de2ef7923e
Minor refactoring, fixes (#63766)
A couple of minor changes to minimize the diff for "large completions
API refactoring".

Most changes are just a refactoring of the `openai` completions
provider, which I apparently missed in
https://github.com/sourcegraph/sourcegraph/pull/63731. (There are still
some smaller tweaks that can be made to the `fireworks` or `google`
completion providers, but they aren't as meaningful.

This PR also removes a couple of unused fields and methods. e.g.
`types.CompletionRequestParameters::Prompt`. There was a comment to the
effect of it being long since deprecated, and it is no longer read
anywhere on the server side. So I'm assuming that a green CI/CD build
means it is safe to remove.

## Test plan

CI/CD

## Changelog

NA
2024-07-10 14:27:28 -07:00
Chris Smith
e80144e70d
Add more Completions handler tests (#63761)
This PR adds more unit tests for the "Chat Completions" HTTP endpoint.
The goal is to have unit tests for more of the one-off quirks that we
support today, so that we can catch any regressions when refactoring
this code.

This PR adds _another layer_ of test infrastructure to use to streamline
writing completion tests. (Since they are kinda involved, and are
mocking out multiple interactions, it's kinda necessary.)

It introduces a new data type `completionsRequestTestData` which
contains all of the "inputs" to the test case, as well as some of the
things we want to validate.

```go
type completionsRequestTestData struct {
	SiteConfig schema.SiteConfiguration
	UserCompletionRequest types.CodyCompletionRequestParameters
	WantRequestToLLMProvider map[string]any
	WantRequestToLLMProviderPath string
	ResponseFromLLMProvider map[string]any
	WantCompletionResponse types.CompletionResponse
}
```

Then to run one of these tests, you just call the new function:

```go
func runCompletionsTest(t *testing.T, infra *apiProviderTestInfra, data completionsRequestTestData) {
```

With this, the new pattern for completion tests is of the form:

```go
func TestProviderX(t *testing.T) {
    // Return a valid site configuration, and the expected API request body
    // we will send to the LLM API provider X.
    getValidTestData := func() completionsRequestTestData {
        ...
    }

    t.Run("TestDataIsValid", func(t *testing.T) {
        // Just confirm that the stock test data works as expected,
        // without any test-specific modifications.
        data := getValidTestData()
        runCompletionsTest(t, infra, data)
    })
}
```

And then, for more sophisticated tests, we would just overwrite whatever
subset of fields are necessary from the stock test data.

For example, testing the way AWS Bedrock provisioned throughput ARNs get
reflected in the completions API can be done by creating a function to
return the specific site configuration data, and then:

```go
	t.Run("Chat", func(t *testing.T) {
			data := getValidTestData()
			data.SiteConfig.Completions = getProvisionedThroughputSiteConfig()

			// The chat model is using provisioned throughput, so the
			// URLs are different.
			data.WantRequestToLLMProviderPath = "/model/arn:aws:bedrock:us-west-2:012345678901:provisioned-model/abcdefghijkl/invoke"

			runCompletionsTest(t, infra, data)
		})

		t.Run("FastChat", func(t *testing.T) {
			data := getValidTestData()
			data.SiteConfig.Completions = getProvisionedThroughputSiteConfig()

			data.UserCompletionRequest.Fast = true

			// The fast chat model does not have provisioned throughput, and
			// so the request path to bedrock just has the model's name. (No ARN.)
			data.WantRequestToLLMProviderPath = "/model/anthropic.claude-v2-fastchat/invoke"

			runCompletionsTest(t, infra, data)
		})
```


## Test plan

Added more unit tests.

## Changelog

NA
2024-07-10 14:10:39 -07:00
Felix Kling
6819363fa0
feat(svelte): Add search query syntax introduction (#63753)
Closes srch-494

This adds the search query syntax introduction component to the search
homepage. I tried to replicate the React version as closely as possible.

I originally wanted to reuse the logic to generate the example sections
but since it had dependencies on wildcard I duplicated it instead.

Notable additional changes:
- Added a `value` method to the temporary settings store to make it
easier to get the current value of the settings store. It only resolves
(or rejects) once the data is loaded.
- Extended the tabs component to not show the tab header if there is
only a single panel. This makes it easier for consumers to render tabs
conditionally.
- Added the `ProductStatusBadge` component
- Various style adjustments

For reference, the relevant parts of the React version are in
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/client/branded/src/search-ui/components/useQueryExamples.tsx
and
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph/-/blob/client/branded/src/search-ui/components/QueryExamples.tsx

## Test plan

Manual testing. I manually set the value received from temporary
settings to `null` (in code) to force trigger the compute logic.
2024-07-10 22:52:28 +02:00
Jean-Hadrien Chabran
087ad83995
chore(release): bump stitch graph generation (#63767)
Missing bit for the minor release version bump

## Test plan

CI

<!-- REQUIRED; info at
https://docs-legacy.sourcegraph.com/dev/background-information/testing_principles
-->
2024-07-10 13:36:02 -07:00
Felix Kling
9072b3a58d
feat(svelte): Add 'y' shortcut to navigate to permalink (#63719)
Fixes srch-589

This implements the 'y' shortcut to navigate to the permalink page, just
like we have in the React app.

According to aria guidelines it should be possible to disable single
character shortcuts but this actually never worked for the 'y' shortcut
because it was implemented differently. So adding it without the option
to turn it off is at least not a regression.

For reference this the code handling the shortcut in the React app:
https://sourcegraph.sourcegraph.com/github.com/sourcegraph/sourcegraph@d9dff1191a3bad812aa5b50315b8e77ee0e40e55/-/blob/client/web/src/repo/actions/CopyPermalinkAction.tsx?L64-77

When initially implementing this I noticed that there is a slight delay
between pressing 'y' and the URL/UI updating. That's because SvelteKit
has to wait for `ResolveRepoRevision` call to resolve before updating
the page. A new request is made because the URL changes which triggers
the data loader. But we already know that such a request will return the
same data, so the request is unnecessary. To avoid the second call I
added another caching layer.

I also noticed that the last commit info would be reloaded which is
unnecessary. I changed the implementation to use the resolved revision
instead of the revision from the URL. Now the request will be properly
cached on the commit ID and the implementation is also much simpler.

## Test plan

Manual testing.
2024-07-10 21:47:14 +02:00
Geoffrey Gilmore
9063f05eb9
feat/graphql/access_tokens: send access token creation/deletion emails in background and create special message for dial errors (#63760)
Closes
https://linear.app/sourcegraph/issue/SRC-463/error-handling-for-smtp-config-issues

Before, when someone created or deleted an access token, we'd block on
sending the email before we'd return to the user.

However, if an error occurred when sending an email - the error was only
logged - **not** returned to the caller.

This PR makes three changes:

1. We now sending the email in a background goroutine. This makes it so
that the caller doesn't have to wait for the email to be sent before
getting the access token back. This isn't a behavior change since we
only logged any SMTP errors and **deliberatly avoided** forwarding that
error to the caller. That behavior doesn't change here.

1. If an error occurs while sending the access token email, we now have
a specialized log message indicating that the user's SMTP configuration
might be incorrect.

1. The log error that's printed is now an `ERROR` instead of a `WARN`
level.

## Test plan

1. On local dev, I edited the credentials in the [dev-private site
configuration file
](67ee9b3a69/enterprise/dev/site-config.json (L8-L11))to
point to an invalid port.

2. I attempted to create an access token, and after only 30 seconds I
saw this error print in the terminal:

```
[       frontend] WARN schemaResolver.CreateAccessToken graphqlbackend/access_tokens.go:150 Failed to send email to inform user of access token creation. (This error might indicate that your SMTP connection settings are incorrect. Please check your site configuration.) {"userID": 1, "error": "establishing TCP connection to \"smtp.gmail.com:57\": dial tcp 142.250.101.109:57: i/o timeout"}
```

3. I fixed the broken SMTP configuration, and deleted the access token.
I saw it suscessfully send an email:

![Screenshot 2024-07-10 at
11.44.07 AM.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/5VKJ5spRdhDRvKQ0TTIe/406e4b23-121f-4d47-a818-430e4ce1b656.png)


## Changelog

- When creating or deleting an access token, we no longer wait for the
email to be sent before returning to the caller. Instead, we now send it
in the background.
2024-07-10 12:43:14 -07:00
Geoffrey Gilmore
fd2c675c2b
fix/internal/txemail: add timeout for SMTP connection establishment (#63759)
Before, the smtp.Dial function had no cancellation mechanism - meaning
that you could be waiting for several minutes to try to establish a
connection before it gives up.

I work around this by establishing a TCP connection myself to the
appropriate address, and using
[net.DialContext](https://pkg.go.dev/net#Dialer.DialContext) to cancel
the dial process if either:

1. The parent context cancels
2. 30 seconds have passed 

Afterwards, we construct the smtp.Client ourselves using
[smtp.NewClient](https://pkg.go.dev/net/smtp#NewClient)

This only changes what happens when we try to establish a connection -
it doesn't change any behavior around sending emails afterwards.

## Test plan

Manual testing. 

1. On local dev, I edited the credentials in the [dev-private site
configuration file
](67ee9b3a69/enterprise/dev/site-config.json (L8-L11))to
point to an invalid port.

2. I attempted to create an access token, and after only30 seconds I saw
this error print in the terminal:

```
[       frontend] WARN schemaResolver.CreateAccessToken graphqlbackend/access_tokens.go:127 Failed to send email to inform user of access token creation {"userID": 1, "error": "establishing TCP connection to \"smtp.gmail.com:57\": dial tcp 74.125.137.109:57: i/o timeout"}
```

## Changelog

- Instead of waiting forever, we wait at most 30 seconds before giving
up when trying to connect to the configured mail server when sending an
email.
2024-07-10 12:34:06 -07:00
Robert Lin
857d5200b3
feat/dotcom: use Enterprise Portal for Cody Gateway usage (#63653)
Closes https://linear.app/sourcegraph/issue/CORE-211

See https://linear.app/sourcegraph/issue/CORE-100 for a higher-level
view - this is the first proof-of-concept for achieving our migration
strategy to extract Enterprise subscription data out of dotcom while
retaining the existing UI until a future project ships a dedicated
Enterprise Portal UI
(https://linear.app/sourcegraph/project/kr-p-enterprise-portal-user-interface-dadd5ff28bd8).

The integration uses generated ConnectRPC client code + `react-query`,
the latter of which has already been used elsewhere for SSC
integrations. This is partly supported by
https://github.com/connectrpc/connect-query-es which offers
mostly-first-class integration with `react-query`, but I had to do some
fenangling to provide the query clients directly as I can't get the
React provider thing to work. The ConnectRPC clients point to the
proxies introduced in
https://github.com/sourcegraph/sourcegraph/pull/63652 which
authenticates the requests for Enterprise Portal, until we ship
https://linear.app/sourcegraph/project/kr-p1-streamlined-role-assignment-via-sams-and-entitle-2f118b3f9d4c/overview

## Test plan

### Local

First, `sg start dotcom`

Choose a subscription you have locally. Use `psql -d sourcegraph` to
connect to local database, then:

```
sourcegraph=# delete from product_licenses where product_subscription_id = '<local subscription ID>';
DELETE 1
sourcegraph=# update product_subscriptions set id = '58b95c21-c2d0-4b4b-8b15-bf1b926d3557' where id = '<local subscription ID>';
UPDATE 1
```

Now annoyingly the UI will break because there is no license, we need:

```gql
query getGraphQLID {
  dotcom {
    productSubscription(uuid:"58b95c21-c2d0-4b4b-8b15-bf1b926d3557") {
      id # graphQL ID
    }
  }
}

mutation createLicense {
  dotcom {
    generateProductLicenseForSubscription(productSubscriptionID:"<graphQLID>", license:{
      tags:["dev"]
      userCount:100
      expiresAt:1814815397
    }) {
      id
    }
  }
}
```

This effectively lets us have a "pretend S2" subscription locally.
Visiting the subscription page now at
https://sourcegraph.test:3443/site-admin/dotcom/product/subscriptions/58b95c21-c2d0-4b4b-8b15-bf1b926d3557


![image](https://github.com/sourcegraph/sourcegraph/assets/23356519/1e77d77d-8032-436b-ab1d-393b34e8e4b5)

The data matches the "real" data currently at
https://sourcegraph.com/site-admin/dotcom/product/subscriptions/58b95c21-c2d0-4b4b-8b15-bf1b926d3557

### Against dotcom

```
sg start web-standalone
```

follow
https://www.loom.com/share/6cb3b3ca475b4b9392aa4b11938e76e6?sid=6cd1a689-d75d-4133-bcff-b0c7d25b23f1
and then check out some product subscriptions
2024-07-10 19:22:08 +00:00
2813 changed files with 99167 additions and 75570 deletions

View File

@ -59,9 +59,4 @@ test --build_event_binary_file_path_conversion=false
test --build_event_binary_file_upload_mode=wait_for_upload_complete
test --build_event_publish_all_actions=true
build --experimental_execution_log_compact_file=execution_log.zstd
test --experimental_execution_log_compact_file=execution_log.zstd
# These likely perform faster locally than the overhead of pulling/pushing from/to the remote cache,
# as well as being able to reduce how much we push to the cache
common --modify_execution_info=CopyDirectory=+no-remote,CopyToDirectory=+no-remote,CopyFile=+no-remote

View File

@ -26,6 +26,7 @@ client/web/node_modules
client/web-sveltekit/node_modules
client/wildcard/node_modules
internal/appliance/frontend/maintenance/node_modules
internal/openapi/node_modules
cmd/symbols/internal/squirrel/test_repos/starlark

View File

@ -30,6 +30,8 @@ const config = {
'typedoc.js',
'client/web/dev/**/*',
'graphql-schema-linter.config.js',
// Generated code
'client/web/src/enterprise/site-admin/dotcom/productSubscriptions/enterpriseportalgen/**',
],
extends: ['@sourcegraph/eslint-config', 'plugin:storybook/recommended'],
env: {
@ -92,6 +94,7 @@ const config = {
'@typescript-eslint/no-unused-vars': 'off', // also duplicated by tsconfig noUnused{Locals,Parameters}
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'etc/no-deprecated': 'off',
'no-restricted-imports': [
@ -111,10 +114,6 @@ const config = {
importNames: ['Link'],
message: 'Use the <Link /> component from @sourcegraph/wildcard instead.',
},
{
name: 'chromatic/isChromatic',
message: 'Please use `isChromatic` from the `@sourcegraph/storybook` package.',
},
],
patterns: [
{

6
.github/CODEOWNERS vendored Normal file
View File

@ -0,0 +1,6 @@
# Sourcegraph uses CODENOTIFY to make individuals or groups aware of changes that are happening in code they care about,
# without explicitly requiring those engineers to "own" the code.
# This file is meant to protect critical code from accidental changes, and should be used sparsingly to prevent slowdowns
# from code reviews.
/internal/tenant/ @sourcegraph/multi-tenant

View File

@ -1,11 +1,12 @@
---
name: Bug report
about: Report problems and unexpected behavior
about: Report problems and unexpected behavior (Code Search ONLY)
title: ''
labels: ''
assignees: ''
---
<!-- Please submit all feedback or bug reports for Cody in the [VS Code](https://github.com/sourcegraph/cody) or [JetBrains](https://github.com/sourcegraph/jetbrains) repo. -->
- **Sourcegraph version:** <!-- the version of Sourcegraph or "Sourcegraph.com" -->
- **Platform information:** <!-- OS version, cloud provider, web browser version, Docker version, etc., depending on the issue -->

112
.github/workflows/cloud-gql-compat.yml vendored Normal file
View File

@ -0,0 +1,112 @@
# Cloud controller has tight integration with GraphQL API
# This workflow ensures that the query/mutation the controller uses are compatible with any changes to the GraphQL schema
#
# Maintained by the Cloud Operation team
name: Cloud Controller GQL Compat Test
on:
pull_request:
paths:
- '**.graphql'
jobs:
run:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/create-github-app-token@v1
id: app-token
with:
# The GitHub App is here:
# https://github.com/organizations/sourcegraph/settings/apps/cloud-srcgql-compat-test-invoker
app-id: ${{ secrets.CLOUD_SRCGQL_COMPAT_TEST_INVOKER_GITHUB_APP_ID }}
private-key: ${{ secrets.CLOUD_SRCGQL_COMPAT_TEST_INVOKER_GITHUB_APP_PRIVATE_KEY_PEM }}
owner: sourcegraph
- uses: lasith-kg/dispatch-workflow@91345a2a3b705e950978a584446ab59f7e815ae3 #v2.0.0
id: workflow-dispatch
with:
dispatch-method: workflow_dispatch
discover: true
repo: controller
owner: sourcegraph
ref: main
# using ID instead of workflow file name to avoid requring content:read permission to the repo
# retrieve by running 'gh workflow list' in the controller repo
workflow: 58413286 # srcgql-compat.yaml
token: ${{ steps.app-token.outputs.token }}
workflow-inputs: |
{
"ref": "${{ github.sha }}",
"upstream_pr_number": "${{ github.event.number }}"
}
- name: await workflow run (id:${{ steps.workflow-dispatch.outputs.run-id }})
uses: codex-/await-remote-run@d4a6dbf57245924ff4f23e0db929b8e3ef65486b #1.12.2
with:
token: ${{ steps.app-token.outputs.token }}
repo: controller
owner: sourcegraph
run_id: ${{ steps.workflow-dispatch.outputs.run-id }}
run_timeout_seconds: 300
poll_interval_ms: 5000
- uses: actions/github-script@v7
if: ${{ success() || failure() }}
env:
FAILED: ${{ job.status == 'failure' }}
RUN_URL: https://github.com/sourcegraph/controller/actions/runs/${{ steps.workflow-dispatch.outputs.run-id }}
with:
script: |
const isFailed = process.env.FAILED === 'true'
const commentMarker = '<!-- cloud-gql-compat-test-result-marker -->'
let message
if (isFailed) {
message = `
## :x: Cloud Controller GraphQL Compatability Test Result
[sourcegraph/controller](https://github.com/sourcegraph/controller) uses the GraphQL API to perform automation. The compatibility test has failed and this pull request may have introduced breaking changes to the GraphQL schema.
Next steps:
- Review the GitHub Actions [workflow logs](${process.env.RUN_URL}) for more details.
- Reach out to the Cloud Ops team to resolve the issue before merging this pull request.
${commentMarker}
`
} else {
message = `
## :white_check_mark: Cloud Controller GraphQL Compatability Test Result
[sourcegraph/controller](https://github.com/sourcegraph/controller) uses the GraphQL API to perform automation. The compatibility test has passed.
Learn more from [workflow logs](${process.env.RUN_URL}).
${commentMarker}
`
}
const { data: comments } = await github.rest.issues.listComments({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
per_page: 100,
})
let existingComment = comments.find(comment => comment.body.includes(commentMarker))
if (existingComment) {
await github.rest.issues.updateComment({
comment_id: existingComment.id,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
})
} else if (isFailed) {
// we only create comment if the test failed
await github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
})
}

View File

@ -1,21 +1,21 @@
# See https://docs.sourcegraph.com/dev/background-information/ci#pr-auditor
name: pr-auditor
on:
pull_request_target:
types: [ closed, edited, opened, synchronize, ready_for_review ]
workflow_dispatch:
jobs:
check-pr:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
repository: 'sourcegraph/pr-auditor'
repository: 'sourcegraph/devx-service'
token: ${{ secrets.PR_AUDITOR_TOKEN }}
- uses: actions/setup-go@v4
with: { go-version: '1.22' }
- run: './check-pr.sh'
- run: 'go run ./cmd/pr-auditor'
env:
GITHUB_EVENT_PATH: ${{ env.GITHUB_EVENT_PATH }}
GITHUB_TOKEN: ${{ secrets.PR_AUDITOR_TOKEN }}

View File

@ -70,3 +70,6 @@ dev/linearhooks/internal/lineargql/schema.graphql
# This is an embedded external minified library and should not be modified
internal/appliance/web/static/script/htmx.min.js
internal/appliance/web/static/script/bootstrap.bundle.min.js
# Generated code
client/web/src/enterprise/site-admin/dotcom/productSubscriptions/enterpriseportalgen/**

View File

@ -1,4 +1,4 @@
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag", "bool_setting")
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
load("@io_bazel_rules_go//go:def.bzl", "go_library", "nogo")
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin")
load("@aspect_rules_ts//ts:defs.bzl", "ts_config")
@ -271,17 +271,6 @@ go_proto_compiler(
],
)
# Settings for automatic building of frontend/single-server without client bundle included
bool_setting(
name = "integration_testing",
build_setting_default = False,
)
config_setting(
name = "integration_testing_enabled",
flag_values = {":integration_testing": "true"},
)
# nogo config
#
# For nogo to be able to run a linter, it needs to have `var Analyzer analysis.Analyzer` defined in the main package.
@ -307,6 +296,7 @@ nogo(
"//conditions:default": [
"//dev/linters/bodyclose",
"//dev/linters/depguard",
"//dev/linters/exhaustruct",
"//dev/linters/forbidigo",
"//dev/linters/gocheckcompilerdirectives",
"//dev/linters/gocritic",

View File

@ -37,6 +37,7 @@ All notable changes to Sourcegraph are documented in this file.
- The default and recommended chat model for Anthropic and Cody Gateway configurations is now `claude-3-sonnet-20240229`. [#62757](https://github.com/sourcegraph/sourcegraph/pull/62757)
- The default and recommended autocomplete model for Cody Gateway configurations is now `fireworks/starcoder`. [#62757](https://github.com/sourcegraph/sourcegraph/pull/62757)
- Code Insights: Language Stats Insights performance improved by another 70-90%. It's now able to handle repositories above 40 GB. [#62946](https://github.com/sourcegraph/sourcegraph/pull/62946)
- The keyword search toggle has been removed from the search results page. [Keyword search](https://sourcegraph.com/docs/code-search/queries#keyword-search-default) is now enabled by default for all searches in the Sourcegraph web app. [#63584](https://github.com/sourcegraph/sourcegraph/pull/63584)
### Fixed

View File

@ -28,30 +28,30 @@ bazel_skylib_workspace()
http_archive(
name = "aspect_bazel_lib",
sha256 = "6d758a8f646ecee7a3e294fbe4386daafbe0e5966723009c290d493f227c390b",
strip_prefix = "bazel-lib-2.7.7",
url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.7.7/bazel-lib-v2.7.7.tar.gz",
sha256 = "c780120ab99a4ca9daac69911eb06434b297214743ee7e0a1f1298353ef686db",
strip_prefix = "bazel-lib-2.7.9",
url = "https://github.com/aspect-build/bazel-lib/releases/download/v2.7.9/bazel-lib-v2.7.9.tar.gz",
)
http_archive(
name = "aspect_rules_js",
sha256 = "3bad4ab669d4d38d0d137275b946a46ce6f8f17fecc6c7affba64966a9054246",
strip_prefix = "rules_js-2.0.0-rc5",
url = "https://github.com/aspect-build/rules_js/releases/download/v2.0.0-rc5/rules_js-v2.0.0-rc5.tar.gz",
sha256 = "f8536470864c91f91c83aea91de9a27607ca5e6d8a9fcdd56132cf422c6b7b56",
strip_prefix = "rules_js-2.0.0-rc9",
url = "https://github.com/aspect-build/rules_js/releases/download/v2.0.0-rc9/rules_js-v2.0.0-rc9.tar.gz",
)
http_archive(
name = "aspect_rules_ts",
sha256 = "3ea5cdb825d5dbffe286b3d9c5197a2648cf04b5e6bd8b913a45823cdf0ae960",
strip_prefix = "rules_ts-3.0.0-rc0",
url = "https://github.com/aspect-build/rules_ts/releases/download/v3.0.0-rc0/rules_ts-v3.0.0-rc0.tar.gz",
sha256 = "1d745fd7a5ffdb5bb7c0b77b36b91409a5933c0cbe25af32b05d90e26b7d14a7",
strip_prefix = "rules_ts-3.0.0-rc2",
url = "https://github.com/aspect-build/rules_ts/releases/download/v3.0.0-rc2/rules_ts-v3.0.0-rc2.tar.gz",
)
http_archive(
name = "aspect_rules_swc",
sha256 = "c085647585c3d01bee3966eb9ba433a1efbb0ee79bb1b8c67882a81d82a9b37f",
strip_prefix = "rules_swc-2.0.0-rc0",
url = "https://github.com/aspect-build/rules_swc/releases/download/v2.0.0-rc0/rules_swc-v2.0.0-rc0.tar.gz",
sha256 = "0c2e8912725a1d97a37bb751777c9846783758f5a0a8e996f1b9d21cad42e839",
strip_prefix = "rules_swc-2.0.0-rc1",
url = "https://github.com/aspect-build/rules_swc/releases/download/v2.0.0-rc1/rules_swc-v2.0.0-rc1.tar.gz",
)
http_archive(
@ -106,9 +106,9 @@ http_archive(
# Container rules
http_archive(
name = "rules_oci",
sha256 = "647f4c6fd092dc7a86a7f79892d4b1b7f1de288bdb4829ca38f74fd430fcd2fe",
strip_prefix = "rules_oci-1.7.6",
url = "https://github.com/bazel-contrib/rules_oci/releases/download/v1.7.6/rules_oci-v1.7.6.tar.gz",
sha256 = "311e78803a4161688cc79679c0fb95c56445a893868320a3caf174ff6e2c383b",
strip_prefix = "rules_oci-2.0.0-beta2",
url = "https://github.com/bazel-contrib/rules_oci/releases/download/v2.0.0-beta2/rules_oci-v2.0.0-beta2.tar.gz",
)
http_archive(
@ -407,15 +407,9 @@ load("@rules_oci//oci:dependencies.bzl", "rules_oci_dependencies")
rules_oci_dependencies()
load("@rules_oci//oci:repositories.bzl", "LATEST_CRANE_VERSION", "oci_register_toolchains")
load("@rules_oci//oci:repositories.bzl", "oci_register_toolchains")
oci_register_toolchains(
name = "oci",
crane_version = LATEST_CRANE_VERSION,
# Uncommenting the zot toolchain will cause it to be used instead of crane for some tasks.
# Note that it does not support docker-format images.
# zot_version = LATEST_ZOT_VERSION,
)
oci_register_toolchains(name = "oci")
# Optional, for oci_tarball rule
load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies")
@ -501,7 +495,7 @@ load("//dev:schema_migrations.bzl", "schema_migrations")
schema_migrations(
name = "schemas_migrations",
updated_at = "2024-07-10 23:24",
updated_at = "2024-08-07 19:10",
)
# wolfi images setup ================================

View File

@ -36,12 +36,6 @@ export const Interactive: StoryFn = () => {
return <ToggleExample value={value} onToggle={onToggle} />
}
Interactive.parameters = {
chromatic: {
disable: true,
},
}
export const Variants: StoryFn = () => (
<>
<ToggleExample value={true} onToggle={onToggle} />

View File

@ -13,11 +13,7 @@ const decorator: Decorator = story => (
const config: Meta = {
title: 'branded/TabbedPanelContent',
decorators: [decorator],
parameters: {
chromatic: {
viewports: [320, 576, 978, 1440],
},
},
parameters: {},
}
export default config

View File

@ -7,9 +7,7 @@ import { type RepoMetadataItem, RepoMetadata } from './RepoMetadata'
const config: Meta = {
title: 'branded/search-ui/RepoMetadata',
parameters: {
chromatic: { viewports: [480] },
},
parameters: {},
}
export default config
@ -50,8 +48,3 @@ export const RepoMetadataStory: StoryFn = () => (
)
RepoMetadataStory.storyName = 'RepoMetadata'
RepoMetadataStory.parameters = {
chromatic: {
disableSnapshot: false,
},
}

View File

@ -8,9 +8,7 @@ import { SyntaxHighlightedSearchQuery } from './SyntaxHighlightedSearchQuery'
const config: Meta = {
title: 'branded/search-ui/SyntaxHighlightedSearchQuery',
parameters: {
chromatic: { viewports: [480] },
},
parameters: {},
}
export default config

View File

@ -10,9 +10,7 @@ import { BaseCodeMirrorQueryInput, type BaseCodeMirrorQueryInputProps } from './
const config: Meta = {
title: 'branded/search-ui/input/BaseCodeMirrorQueryInput',
parameters: {
chromatic: { viewports: [500] },
},
parameters: {},
}
export default config

View File

@ -16,9 +16,7 @@ import { SearchBox, type SearchBoxProps } from './SearchBox'
const config: Meta = {
title: 'branded/search-ui/input/SearchBox',
parameters: {
chromatic: { viewports: [575, 700], disableSnapshot: false },
},
parameters: {},
}
export default config

View File

@ -22,7 +22,6 @@ const decorator: Decorator = story => (
const config: Meta = {
title: 'branded/search-ui/input/SearchContextMenu',
parameters: {
chromatic: { viewports: [500], disableSnapshot: false },
design: {
type: 'figma',
url: 'https://www.figma.com/file/4Fy9rURbfF2bsl4BvYunUO/RFC-261-Search-Contexts?node-id=581%3A4754',

View File

@ -13,9 +13,7 @@ const decorator: Decorator = story => (
const config: Meta = {
title: 'branded/search-ui/input/SearchContextMenuItem',
parameters: {
chromatic: { viewports: [1200], disableSnapshot: false },
},
parameters: {},
decorators: [decorator],
}

View File

@ -11,9 +11,7 @@ const decorator: Decorator = story => <BrandedStory>{props => story()}</BrandedS
const config: Meta = {
title: 'branded/search-ui/filters',
decorators: [decorator],
parameters: {
chromatic: { viewports: [575, 700] },
},
parameters: {},
}
export default config

View File

@ -15,7 +15,6 @@ const config: Meta = {
type: 'figma',
url: 'https://www.figma.com/file/IyiXZIbPHK447NCXov0AvK/13928-Streaming-search?node-id=280%3A17768',
},
chromatic: { viewports: [1200], disableSnapshot: false },
},
}

View File

@ -14,7 +14,6 @@ const config: Meta = {
type: 'figma',
url: 'https://www.figma.com/file/IyiXZIbPHK447NCXov0AvK/13928-Streaming-search?node-id=280%3A17768',
},
chromatic: { viewports: [350], disableSnapshot: false },
},
}

View File

@ -356,7 +356,7 @@ export const ExhaustiveSearchMessage: FC<ExhaustiveSearchMessageProps> = props =
if (!validationLoading) {
telemetryService.log('SearchJobsSearchFormShown', { validState }, { validState })
telemetryRecorder.recordEvent('search.exhaustiveJobs', 'view', {
metadata: { validState: validState ? 1 : 0 },
metadata: { validState: validState === 'valid' ? 1 : 0 },
})
}
}, [telemetryService, telemetryRecorder, validationError, validationLoading])

View File

@ -8,12 +8,7 @@ import brandedStyles from '../../branded.scss'
const config: Meta = {
title: 'browser/AfterInstallPage',
parameters: {
chromatic: {
enableDarkMode: true,
disableSnapshot: false,
},
},
parameters: {},
}
export default config

View File

@ -162,10 +162,3 @@ AllOptionsPages.args = {
version: '0.0.0',
showSourcegraphComAlert: false,
}
AllOptionsPages.parameters = {
chromatic: {
enableDarkMode: true,
disableSnapshot: false,
},
}

View File

@ -52,8 +52,8 @@ describe('GitHub', () => {
})
testContext.overrideGraphQL({
ViewerConfiguration: () => ({
viewerConfiguration: {
ViewerSettings: () => ({
viewerSettings: {
subjects: [],
merged: { contents: '', messages: [] },
},
@ -158,8 +158,8 @@ describe('GitHub', () => {
// extensions: extensionSettings,
// }
// testContext.overrideGraphQL({
// ViewerConfiguration: () => ({
// viewerConfiguration: {
// ViewerSettings: () => ({
// viewerSettings: {
// subjects: [
// {
// __typename: 'User',
@ -321,8 +321,8 @@ describe('GitHub', () => {
extensions: extensionSettings,
}
testContext.overrideGraphQL({
ViewerConfiguration: () => ({
viewerConfiguration: {
ViewerSettings: () => ({
viewerSettings: {
subjects: [
{
__typename: 'User',
@ -643,8 +643,8 @@ describe('GitHub', () => {
extensions: extensionSettings,
}
testContext.overrideGraphQL({
ViewerConfiguration: () => ({
viewerConfiguration: {
ViewerSettings: () => ({
viewerSettings: {
subjects: [
{
__typename: 'User',

View File

@ -47,8 +47,8 @@ describe('GitLab', () => {
})
testContext.overrideGraphQL({
ViewerConfiguration: () => ({
viewerConfiguration: {
ViewerSettings: () => ({
viewerSettings: {
subjects: [],
merged: { contents: '', messages: [] },
},
@ -152,8 +152,8 @@ describe('GitLab', () => {
extensions: extensionSettings,
}
testContext.overrideGraphQL({
ViewerConfiguration: () => ({
viewerConfiguration: {
ViewerSettings: () => ({
viewerSettings: {
subjects: [
{
__typename: 'User',

View File

@ -28,12 +28,7 @@ const config: Meta = {
// it uses the browser extension styles and bitbucket CSS module styles.
title: 'shared/HoverOverlay',
decorators: [decorator],
parameters: {
chromatic: {
enableDarkMode: true,
disableSnapshot: false,
},
},
parameters: {},
}
export default config

View File

@ -14,7 +14,7 @@ import {
} from '@sourcegraph/shared/src/settings/settings'
import { observeStorageKey, storage } from '../../browser-extension/web-extension-api/storage'
import type { ViewerConfigurationResult } from '../../graphql-operations'
import type { ViewerSettingsResult } from '../../graphql-operations'
import { isInPage } from '../context'
const inPageClientSettingsKey = 'sourcegraphClientSettings'
@ -35,7 +35,8 @@ function observeLocalStorageKey(key: string, defaultValue: string): Observable<s
}
const createStorageSettingsCascade: () => Observable<SettingsCascade> = () => {
/** Observable of the JSONC string of the settings.
/**
* Observable of the JSONC string of the settings.
*
* NOTE: We can't use LocalStorageSubject here because the JSONC string is stored raw in localStorage and LocalStorageSubject also does parsing.
* This could be changed, but users already have settings stored, so it would need a migration for little benefit.
@ -95,9 +96,8 @@ export function mergeCascades(
}
}
// This is a fragment on the DEPRECATED GraphQL API type ConfigurationCascade (not SettingsCascade) for backcompat.
const configurationCascadeFragment = gql`
fragment ConfigurationCascadeFields on ConfigurationCascade {
const settingsCascadeFragment = gql`
fragment SettingsCascadeFields on SettingsCascade {
subjects {
__typename
...OrgSettingFields
@ -167,42 +167,40 @@ const configurationCascadeFragment = gql`
/**
* Fetches the settings cascade for the viewer.
*
* TODO(sqs): This uses the DEPRECATED GraphQL Query.viewerConfiguration and ConfigurationCascade for backcompat.
*/
export function fetchViewerSettings(requestGraphQL: PlatformContext['requestGraphQL']): Observable<{
final: string
subjects: SettingsSubject[]
}> {
return from(
requestGraphQL<ViewerConfigurationResult>({
requestGraphQL<ViewerSettingsResult>({
request: gql`
query ViewerConfiguration {
viewerConfiguration {
...ConfigurationCascadeFields
query ViewerSettings {
viewerSettings {
...SettingsCascadeFields
}
}
${configurationCascadeFragment}
${settingsCascadeFragment}
`,
variables: {},
mightContainPrivateInfo: false,
})
).pipe(
map(dataOrThrowErrors),
map(({ viewerConfiguration }) => {
if (!viewerConfiguration) {
throw new Error('fetchViewerSettings: empty viewerConfiguration')
map(({ viewerSettings }) => {
if (!viewerSettings) {
throw new Error('fetchViewerSettings: empty viewerSettings')
}
for (const subject of viewerConfiguration.subjects) {
for (const subject of viewerSettings.subjects) {
// User/org/global settings cannot be edited from the
// browser extension (only client settings can).
subject.viewerCanAdminister = false
}
return {
subjects: viewerConfiguration.subjects,
final: viewerConfiguration.merged.contents,
subjects: viewerSettings.subjects,
final: viewerSettings.merged.contents,
}
})
)

View File

@ -150,7 +150,9 @@ function highlightNodeHelper(
}
let newNode: Node
if (newNodes.length === 1) {
if (newNodes.length === 0) {
newNode = document.createTextNode('')
} else if (newNodes.length === 1) {
// If we only have one new node, no need to wrap it in a containing span
newNode = newNodes[0]
} else {

View File

@ -41,6 +41,42 @@ export const highlightCodeSafe = (code: string, language?: string): string => {
}
}
export interface RenderMarkdownOptions {
/**
* Whether to render markdown inline, without paragraph tags
*/
inline?: boolean
/**
* Whether to render line breaks as HTML `<br>`s
*/
breaks?: boolean
/**
* Whether to disable autolinks. Explicit links using `[text](url)` are still allowed.
*/
disableAutolinks?: boolean
/**
* A custom renderer to use
*/
renderer?: marked.Renderer
/**
* A prefix to add to all header IDs
*/
headerPrefix?: string
/**
* Strip off any HTML and return a plain text string, useful for previews
*/
plainText?: boolean
/**
* DOMPurify configuration to use
*/
dompurifyConfig?: DOMPurifyConfig & { RETURN_DOM_FRAGMENT?: false; RETURN_DOM?: false }
/**
* Add target="_blank" and rel="noopener" to all <a> links that have a href value.
* This affects all markdown-formatted links and all inline HTML links.
*/
addTargetBlankToAllLinks?: boolean
}
/**
* Renders the given markdown to HTML, highlighting code and sanitizing dangerous HTML.
* Can throw an exception on parse errors.
@ -55,18 +91,7 @@ export const highlightCodeSafe = (code: string, language?: string): string => {
* @param options.addTargetBlankToAllLinks Add target="_blank" and rel="noopener" to all <a> links
* that have a href value. This affects all markdown-formatted links and all inline HTML links.
*/
export const renderMarkdown = (
markdown: string,
options: {
breaks?: boolean
disableAutolinks?: boolean
renderer?: marked.Renderer
headerPrefix?: string
plainText?: boolean
dompurifyConfig?: DOMPurifyConfig & { RETURN_DOM_FRAGMENT?: false; RETURN_DOM?: false }
addTargetBlankToAllLinks?: boolean
} = {}
): string => {
export const renderMarkdown = (markdown: string, options: RenderMarkdownOptions = {}): string => {
const tokenizer = new marked.Tokenizer()
if (options.disableAutolinks) {
// Why the odd double-casting below?
@ -76,7 +101,7 @@ export const renderMarkdown = (
tokenizer.url = () => undefined as unknown as marked.Tokens.Link
}
const rendered = marked(markdown, {
const rendered = (options.inline ? marked.parseInline : marked)(markdown, {
gfm: true,
breaks: options.breaks,
highlight: (code, language) => highlightCodeSafe(code, language),

View File

@ -86,9 +86,3 @@ export const JetBrainsSearchBoxStory: StoryFn = () => {
</WildcardThemeContext.Provider>
)
}
JetBrainsSearchBoxStory.parameters = {
chromatic: {
disableSnapshot: false,
},
}

View File

@ -123,9 +123,3 @@ export const JetBrainsSearchResultListStory: StoryFn = () => {
</div>
)
}
JetBrainsSearchResultListStory.parameters = {
chromatic: {
disableSnapshot: false,
},
}

View File

@ -30,4 +30,4 @@
"@sourcegraph/wildcard": "workspace:*"
},
"sideEffects": true
}
}

View File

@ -63,12 +63,6 @@ export const CommandAction: StoryFn = () => (
)
CommandAction.storyName = 'Command action'
CommandAction.parameters = {
chromatic: {
enableDarkMode: true,
disableSnapshot: false,
},
}
export const LinkAction: StoryFn = () => (
<ActionItem

View File

@ -31,7 +31,6 @@ export const currentAuthStateQuery = gql`
__typename
id
name
displayName
url
settingsURL
}

View File

@ -23,7 +23,7 @@ import { parseRepoGitURI } from '../util/url'
import type { DocumentSelector, TextDocument, DocumentHighlight } from './legacy-extensions/api'
import * as sourcegraph from './legacy-extensions/api'
import type { LanguageSpec } from './legacy-extensions/language-specs/language-spec'
import { languageSpecs } from './legacy-extensions/language-specs/languages'
import { findLanguageSpec, languageSpecs } from './legacy-extensions/language-specs/languages'
import { RedactingLogger } from './legacy-extensions/logging'
import { createProviders, emptySourcegraphProviders, type SourcegraphProviders } from './legacy-extensions/providers'
import { SymbolRole, Occurrence } from './scip'
@ -172,12 +172,7 @@ const languages: Language[] = languageSpecs.map(spec => ({
// Returns true if the provided language supports "Find implementations"
export function hasFindImplementationsSupport(language: string): boolean {
for (const spec of languageSpecs) {
if (spec.languageID === language) {
return spec.textDocumentImplemenationSupport ?? false
}
}
return false
return findLanguageSpec(language)?.textDocumentImplemenationSupport ?? false
}
function selectorForSpec(languageSpec: LanguageSpec): DocumentSelector {

View File

@ -431,5 +431,6 @@ export const languageSpecs: LanguageSpec[] = [
* @deprecated See FIXME(id: language-detection)
*/
export function findLanguageSpec(languageID: string): LanguageSpec | undefined {
languageID = languageID.toLowerCase()
return languageSpecs.find(spec => spec.languageID === languageID || spec.additionalLanguages?.includes(languageID))
}

View File

@ -2,6 +2,7 @@ import gql from 'tagged-template-noop'
import { isErrorLike } from '@sourcegraph/common'
import { SearchVersion } from '../../../graphql-operations'
import type * as sourcegraph from '../api'
import { cache } from '../util'
@ -251,6 +252,7 @@ export class API {
const data = await queryGraphQL<Response>(buildSearchQuery(fileLocal), {
query,
version: SearchVersion.V3,
})
return data.search.results.results.filter(isDefined)
}
@ -322,8 +324,8 @@ function buildSearchQuery(fileLocal: boolean): string {
if (fileLocal) {
return gql`
query LegacyCodeIntelSearch2($query: String!) {
search(query: $query) {
query LegacyCodeIntelSearch2($query: String!, $version: SearchVersion!) {
search(query: $query, version: $version) {
...SearchResults
...FileLocal
}
@ -334,8 +336,8 @@ function buildSearchQuery(fileLocal: boolean): string {
}
return gql`
query LegacyCodeIntelSearch3($query: String!) {
search(query: $query) {
query LegacyCodeIntelSearch3($query: String!, $version: SearchVersion!) {
search(query: $query, version: $version) {
...SearchResults
}
}

View File

@ -2,6 +2,8 @@
// but it doesn't make sense to do so right now.
import type * as extensions from '@sourcegraph/extension-api-types'
import { CodeGraphDataProvenance } from '../graphql-operations'
import type * as sourcegraph from './legacy-extensions/api'
export interface JsonDocument {
@ -144,7 +146,8 @@ export class Occurrence {
public readonly range: Range,
public readonly kind?: SyntaxKind,
public readonly symbol?: string,
public readonly symbolRoles?: number
public readonly symbolRoles?: number,
public readonly symbolProvenance?: CodeGraphDataProvenance
) {}
public withStartPosition(newStartPosition: Position): Occurrence {

View File

@ -1675,40 +1675,40 @@ describe('scanSearchQuery() and decorate()', () => {
test('highlight repo:has predicate', () => {
expect(getTokens(toSuccess(scanSearchQuery('repo:has(key:value)')))).toMatchInlineSnapshot(`
[
{
"startIndex": 0,
"scopes": "field"
},
{
"startIndex": 4,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 5,
"scopes": "metaPredicateNameAccess"
},
{
"startIndex": 8,
"scopes": "metaPredicateParenthesis"
},
{
"startIndex": 9,
"scopes": "identifier"
},
{
"startIndex": 12,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 13,
"scopes": "identifier"
},
{
"startIndex": 18,
"scopes": "metaPredicateParenthesis"
}
]
[
{
"startIndex": 0,
"scopes": "field"
},
{
"startIndex": 4,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 5,
"scopes": "metaPredicateNameAccess"
},
{
"startIndex": 8,
"scopes": "metaPredicateParenthesis"
},
{
"startIndex": 9,
"scopes": "identifier"
},
{
"startIndex": 12,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 13,
"scopes": "identifier"
},
{
"startIndex": 18,
"scopes": "metaPredicateParenthesis"
}
]
`)
})
@ -1891,6 +1891,103 @@ describe('scanSearchQuery() and decorate()', () => {
`)
})
test('decorate repo:has.meta with regexp', () => {
expect(
getTokens(
toSuccess(
scanSearchQuery(String.raw`repo:has.meta(/abc.*/:/[def]+/)`, false, SearchPatternType.keyword)
)
)
).toMatchInlineSnapshot(`
[
{
"startIndex": 0,
"scopes": "field"
},
{
"startIndex": 4,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 5,
"scopes": "metaPredicateNameAccess"
},
{
"startIndex": 8,
"scopes": "metaPredicateDot"
},
{
"startIndex": 9,
"scopes": "metaPredicateNameAccess"
},
{
"startIndex": 13,
"scopes": "metaPredicateParenthesis"
},
{
"startIndex": 14,
"scopes": "metaRegexpDelimited"
},
{
"startIndex": 15,
"scopes": "identifier"
},
{
"startIndex": 18,
"scopes": "metaRegexpCharacterSet"
},
{
"startIndex": 19,
"scopes": "metaRegexpRangeQuantifier"
},
{
"startIndex": 20,
"scopes": "metaRegexpDelimited"
},
{
"startIndex": 21,
"scopes": "metaFilterSeparator"
},
{
"startIndex": 22,
"scopes": "metaRegexpDelimited"
},
{
"startIndex": 23,
"scopes": "metaRegexpCharacterClass"
},
{
"startIndex": 24,
"scopes": "metaRegexpCharacterClassMember"
},
{
"startIndex": 25,
"scopes": "metaRegexpCharacterClassMember"
},
{
"startIndex": 26,
"scopes": "metaRegexpCharacterClassMember"
},
{
"startIndex": 27,
"scopes": "metaRegexpCharacterClass"
},
{
"startIndex": 28,
"scopes": "metaRegexpRangeQuantifier"
},
{
"startIndex": 29,
"scopes": "metaRegexpDelimited"
},
{
"startIndex": 30,
"scopes": "metaPredicateParenthesis"
}
]
`)
})
test('do not decorate quotes inside quoted filter values', () => {
expect(getTokens(toSuccess(scanSearchQuery(String.raw`file:"foo\"bar"`, false, SearchPatternType.keyword))))
.toMatchInlineSnapshot(`

View File

@ -13,8 +13,8 @@ import type {
import { SearchPatternType } from '../../graphql-operations'
import { type Predicate, scanPredicate } from './predicates'
import { scanSearchQuery } from './scanner'
import { type PredicateInstance, scanPredicate } from './predicates'
import { quoted, scanSearchQuery, oneOf, ScanResult, toPatternResult } from './scanner'
import { type Token, type Pattern, type Literal, PatternKind, type CharacterRange, createLiteral } from './token'
/* eslint-disable unicorn/better-regex */
@ -200,7 +200,7 @@ export interface MetaPredicate {
range: CharacterRange
groupRange?: CharacterRange
kind: MetaPredicateKind
value: Predicate
value: PredicateInstance
}
enum MetaKeywordKind {
@ -1014,33 +1014,48 @@ const decorateRepoHasMetaBody = (body: string, offset: number): DecoratedToken[]
return undefined
}
const offsetToken = (offset: number) => (token: DecoratedToken) => {
token.range.start += offset
token.range.end += offset
return token
}
return [
{
type: 'literal',
value: matches[1],
range: { start: offset, end: offset + matches[1].length },
quoted: false,
},
...(decoratePattern(matches[1])?.map(offsetToken(offset)) ?? []),
{
type: 'metaFilterSeparator',
range: { start: offset + matches[1].length, end: offset + matches[1].length + 1 },
value: ':',
},
{
type: 'literal',
value: matches[1],
range: { start: offset + matches[1].length + 1, end: offset + matches[1].length + 1 + matches[2].length },
quoted: false,
},
...(decoratePattern(matches[2])?.map(offsetToken(offset + matches[1].length + 1)) ?? []),
]
}
const decoratePattern = (token: string): DecoratedToken[] | undefined => {
const plainString = (token: string, offset: number): ScanResult<Literal> => ({
type: 'success',
term: createLiteral(token, { start: offset, end: offset + token.length }),
})
const scanner = oneOf<Pattern>(
toPatternResult(quoted("'"), PatternKind.Literal),
toPatternResult(quoted('"'), PatternKind.Literal),
toPatternResult(quoted('/'), PatternKind.Regexp),
toPatternResult(plainString, PatternKind.Literal)
)
const scanResult = scanner(token, 0)
if (scanResult.type === 'error') {
return undefined
}
return decorate(scanResult.term)
}
/**
* Decorates the body part of predicate syntax `name(body)`.
*/
const decoratePredicateBody = (path: string[], body: string, offset: number): DecoratedToken[] => {
const decoratePredicateBody = (name: string, body: string, offset: number): DecoratedToken[] => {
const decorated: DecoratedToken[] = []
switch (path.join('.')) {
switch (name) {
case 'contains.file':
case 'has.file': {
const result = decorateContainsFileBody(body, offset)
@ -1108,18 +1123,18 @@ const decoratePredicateBody = (path: string[], body: string, offset: number): De
return decorated
}
const decoratePredicate = (predicate: Predicate, range: CharacterRange): DecoratedToken[] => {
const decoratePredicate = (predicate: PredicateInstance, range: CharacterRange): DecoratedToken[] => {
let offset = range.start
const decorated: DecoratedToken[] = []
for (const nameAccess of predicate.path) {
for (const namePart of predicate.name.split('.')) {
decorated.push({
type: 'metaPredicate',
kind: MetaPredicateKind.NameAccess,
range: { start: offset, end: offset + nameAccess.length },
range: { start: offset, end: offset + namePart.length },
groupRange: range,
value: predicate,
})
offset = offset + nameAccess.length
offset = offset + namePart.length
decorated.push({
type: 'metaPredicate',
kind: MetaPredicateKind.Dot,
@ -1140,7 +1155,7 @@ const decoratePredicate = (predicate: Predicate, range: CharacterRange): Decorat
value: predicate,
})
offset = offset + 1
decorated.push(...decoratePredicateBody(predicate.path, body, offset))
decorated.push(...decoratePredicateBody(predicate.name, body, offset))
offset = offset + body.length
decorated.push({
type: 'metaPredicate',

View File

@ -76,7 +76,7 @@ describe('getDiagnostics()', () => {
[
{
"severity": "error",
"message": "Invalid filter value, expected one of: diff, commit, symbol, repo, path, file.",
"message": "Invalid filter value, expected one of: commit, diff, file, path, repo, symbol.",
"range": {
"start": 10,
"end": 15

View File

@ -322,32 +322,33 @@ export const FILTERS: Record<NegatableFilter, NegatableFilterDefinition> &
},
[FilterType.type]: {
description: 'Limit results to diffs, commits, file paths, symbols and other entities.',
discreteValues: () => [
{
label: 'diff',
description: 'Search for file changes',
},
{
label: 'commit',
description: 'Search in commit messages',
},
{
label: 'symbol',
description: 'Search for symbol names',
},
{
label: 'repo',
description: 'Search for repositories',
},
{
label: 'path',
description: 'Search for file/directory names',
},
{
label: 'file',
description: 'Search for file content',
},
],
discreteValues: () =>
[
{
label: 'diff',
description: 'Search for file changes',
},
{
label: 'commit',
description: 'Search in commit messages',
},
{
label: 'symbol',
description: 'Search for symbol names',
},
{
label: 'repo',
description: 'Search for repositories',
},
{
label: 'path',
description: 'Search for file/directory names',
},
{
label: 'file',
description: 'Search for file content',
},
].sort((a, b) => a.label.localeCompare(b.label)),
},
[FilterType.visibility]: {
discreteValues: () => ['any', 'private', 'public'].map(value => ({ label: value })),

View File

@ -197,7 +197,7 @@ const toSelectorHover = (token: MetaSelector): string => {
const toPredicateHover = (token: MetaPredicate): string => {
const parameters = token.value.parameters.slice(1, -1)
switch (token.value.path.join('.')) {
switch (token.value.name) {
case 'contains.file':
case 'has.file': {
return '**Built-in predicate**. Search only inside repositories that satisfy the specified `path:` and `content:` filters. `path:` and `content:` filters should be regular expressions.'

View File

@ -130,7 +130,7 @@ export const collectMetrics = (query: string): Metrics | undefined => {
if (!predicate) {
continue
}
switch (predicate.path.join('.')) {
switch (predicate.name) {
case 'contains.path': {
count_repo_contains_path += 1
break

View File

@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest'
import { scanPredicate, resolveAccess, PREDICATES } from './predicates'
import { scanPredicate } from './predicates'
expect.addSnapshotSerializer({
serialize: value => (value ? JSON.stringify(value) : 'invalid'),
@ -10,19 +10,19 @@ expect.addSnapshotSerializer({
describe('scanPredicate', () => {
test('scan recognized and valid syntax', () => {
expect(scanPredicate('repo', 'contains.file(content:stuff)')).toMatchInlineSnapshot(
'{"path":["contains","file"],"parameters":"(content:stuff)"}'
'{"field":"repo","name":"contains.file","parameters":"(content:stuff)"}'
)
})
test('scan recognized dot syntax', () => {
expect(scanPredicate('repo', 'contains.commit.after(stuff)')).toMatchInlineSnapshot(
'{"path":["contains","commit","after"],"parameters":"(stuff)"}'
'{"field":"repo","name":"contains.commit.after","parameters":"(stuff)"}'
)
})
test('scan recognized and valid syntax with escapes', () => {
expect(scanPredicate('repo', 'contains.file(content:\\((stuff))')).toMatchInlineSnapshot(
'{"path":["contains","file"],"parameters":"(content:\\\\((stuff))"}'
'{"field":"repo","name":"contains.file","parameters":"(content:\\\\((stuff))"}'
)
})
@ -40,13 +40,13 @@ describe('scanPredicate', () => {
test('resolve field aliases for predicates', () => {
expect(scanPredicate('r', 'contains.file(content:stuff)')).toMatchInlineSnapshot(
'{"path":["contains","file"],"parameters":"(content:stuff)"}'
'{"field":"repo","name":"contains.file","parameters":"(content:stuff)"}'
)
})
test('scan recognized file:contains.content syntax', () => {
expect(scanPredicate('file', 'contains.content(stuff)')).toMatchInlineSnapshot(
'{"path":["contains","content"],"parameters":"(stuff)"}'
'{"field":"file","name":"contains.content","parameters":"(stuff)"}'
)
})
@ -57,28 +57,10 @@ describe('scanPredicate', () => {
test('scan invalid file:contains() syntax', () => {
expect(scanPredicate('file', 'contains(stuff')).toMatchInlineSnapshot('invalid')
})
})
describe('resolveAccess', () => {
test('resolves partial access tree', () => {
expect(resolveAccess(['repo'], PREDICATES)).toMatchInlineSnapshot(
'[{"name":"contains","fields":[{"name":"file"},{"name":"path"},{"name":"content"},{"name":"commit","fields":[{"name":"after"}]}]},{"name":"has","fields":[{"name":"file"},{"name":"path"},{"name":"content"},{"name":"commit","fields":[{"name":"after"}]},{"name":"description"},{"name":"tag"},{"name":"key"},{"name":"meta"},{"name":"topic"}]}]'
test('scan repo:has.meta with regex', () => {
expect(scanPredicate('repo', 'has.meta(/abc.*/:/def.*/)')).toMatchInlineSnapshot(
'{"field":"repo","name":"has.meta","parameters":"(/abc.*/:/def.*/)"}'
)
})
test('resolves partial access tree depth 2', () => {
expect(resolveAccess(['repo', 'contains', 'commit'], PREDICATES)).toMatchInlineSnapshot('[{"name":"after"}]')
})
test('resolves fully qualified path', () => {
expect(resolveAccess(['repo', 'contains', 'file'], PREDICATES)).toMatchInlineSnapshot('[]')
})
test('undefind path', () => {
expect(resolveAccess(['OCOTILLO', 'contains', 'file'], PREDICATES)).toMatchInlineSnapshot('invalid')
})
test('invalid predicate syntax', () => {
expect(resolveAccess(['repo', 'contains'], PREDICATES)).toMatchInlineSnapshot('invalid')
})
})

View File

@ -1,102 +1,39 @@
/* eslint-disable no-template-curly-in-string */
import { type Completion, resolveFieldAlias, FilterType } from './filters'
interface Access {
interface PredicateDefinition {
field: string
name: string
fields?: Access[]
}
/**
* Represents recognized predicate accesses associated with fields. The
* data structure is a tree, where nodes are lists to preserve ordering
* for autocomplete suggestions.
*/
export const PREDICATES: Access[] = [
{
name: 'repo',
fields: [
{
name: 'contains',
fields: [
{ name: 'file' },
{ name: 'path' },
{ name: 'content' },
{
name: 'commit',
fields: [{ name: 'after' }],
},
],
},
{
name: 'has',
fields: [
{ name: 'file' },
{ name: 'path' },
{ name: 'content' },
{
name: 'commit',
fields: [{ name: 'after' }],
},
{ name: 'description' },
{ name: 'tag' },
{ name: 'key' },
{ name: 'meta' },
{ name: 'topic' },
],
},
],
},
{
name: 'file',
fields: [
{
name: 'contains',
fields: [{ name: 'content' }],
},
{
name: 'has',
fields: [{ name: 'content' }, { name: 'owner' }],
},
],
},
{
name: 'rev',
fields: [
{
name: 'at',
fields: [{ name: 'time' }],
},
],
},
// PREDICATES is a registry of predicates, grouped by field they belong to
export const PREDICATES: PredicateDefinition[] = [
{ field: 'repo', name: 'contains.file' },
{ field: 'repo', name: 'contains.path' },
{ field: 'repo', name: 'contains.content' },
{ field: 'repo', name: 'contains.commit.after' },
{ field: 'repo', name: 'contains.commit.after' },
{ field: 'repo', name: 'has' },
{ field: 'repo', name: 'has.file' },
{ field: 'repo', name: 'has.path' },
{ field: 'repo', name: 'has.content' },
{ field: 'repo', name: 'has.commit.after' },
{ field: 'repo', name: 'has.description' },
{ field: 'repo', name: 'has.tag' },
{ field: 'repo', name: 'has.key' },
{ field: 'repo', name: 'has.meta' },
{ field: 'repo', name: 'has.topic' },
{ field: 'file', name: 'contains.content' },
{ field: 'file', name: 'has.content' },
{ field: 'file', name: 'has.owner' },
{ field: 'rev', name: 'at.time' },
]
/** Represents a predicate's components corresponding to the syntax path(parameters). */
export interface Predicate {
path: string[]
export interface PredicateInstance extends PredicateDefinition {
parameters: string
}
/** Returns the access tree for a predicate path. */
export const resolveAccess = (path: string[], tree: Access[]): Access[] | undefined => {
if (path.length === 0) {
return tree
}
// repo:contains() and file:contains() are not supported
if (path.length === 1 && path[0] === 'contains') {
return undefined
}
const subtree = tree.find(value => value.name === path[0])
if (!subtree) {
return undefined
}
if (!subtree.fields) {
return []
}
return resolveAccess(path.slice(1), subtree.fields)
}
// scans a string up to closing parentheses. Examples:
// - `foo` succeeds, parentheses are absent, so it is vacuously balanced
// - `foo(...)` succeeds up to the closing `)`
@ -154,23 +91,22 @@ const scanBalancedParens = (input: string): string | undefined => {
* (1) The (field, name) pair is a recognized predicate.
* (2) The parameters value is well-balanced.
*/
export const scanPredicate = (field: string, value: string): Predicate | undefined => {
export const scanPredicate = (field: string, value: string): PredicateInstance | undefined => {
const match = value.match(/^[.a-z]+/i)
if (!match) {
return undefined
}
const name = match[0]
const path = name.split('.')
// Remove negation from the field for lookup
if (field.startsWith('-')) {
field = field.slice(1)
}
field = resolveFieldAlias(field)
const access = resolveAccess([field, ...path], PREDICATES)
if (!access) {
const predicate = PREDICATES.find(predicate => predicate.field === field && predicate.name === name)
if (!predicate) {
return undefined
}
const rest = value.slice(name.length)
const rest = value.slice(predicate.name.length)
const parameters = scanBalancedParens(rest)
if (!parameters) {
return undefined
@ -179,7 +115,7 @@ export const scanPredicate = (field: string, value: string): Predicate | undefin
return undefined
}
return { path, parameters }
return { ...predicate, parameters }
}
export const predicateCompletion = (field: FilterType): Completion[] => {

View File

@ -93,7 +93,7 @@ const zeroOrMore =
/**
* Returns a {@link Scanner} that succeeds if any of the given scanner succeeds.
*/
const oneOf =
export const oneOf =
<T>(...scanners: Scanner<T>[]): Scanner<T> =>
(input, start) => {
const expected: string[] = []
@ -115,7 +115,7 @@ const oneOf =
* A {@link Scanner} that will attempt to scan delimited strings for an arbitrary
* delimiter. `\` is treated as an escape character for the delimited string.
*/
const quoted =
export const quoted =
(delimiter: string): Scanner<Literal> =>
(input, start) => {
if (input[start] !== delimiter) {
@ -297,7 +297,7 @@ export const scanPredicateValue = (input: string, start: number, field: Literal)
at: start,
}
}
const value = `${result.path.join('.')}${result.parameters}`
const value = `${result.name}${result.parameters}`
return {
type: 'success',
term: createLiteral(value, { start, end: start + value.length }),

View File

@ -3,10 +3,10 @@ import { describe, expect, test } from 'vitest'
import { createAggregateError, isErrorLike } from '@sourcegraph/common'
import {
type CustomMergeFunctions,
gqlToCascade,
merge,
mergeSettings,
type CustomMergeFunctions,
type Settings,
type SettingsCascade,
type SettingsSubject,
@ -198,7 +198,6 @@ describe('mergeSettings', () => {
key: '1',
description: 'global saved query',
query: 'type:diff global',
notify: true,
},
],
},
@ -208,7 +207,6 @@ describe('mergeSettings', () => {
key: '2',
description: 'org saved query',
query: 'type:diff org',
notify: true,
},
],
},
@ -218,7 +216,6 @@ describe('mergeSettings', () => {
key: '3',
description: 'user saved query',
query: 'type:diff user',
notify: true,
},
],
},
@ -229,19 +226,16 @@ describe('mergeSettings', () => {
key: '1',
description: 'global saved query',
query: 'type:diff global',
notify: true,
},
{
key: '2',
description: 'org saved query',
query: 'type:diff org',
notify: true,
},
{
key: '3',
description: 'user saved query',
query: 'type:diff user',
notify: true,
},
],
}))

View File

@ -311,7 +311,6 @@ const defaultFeatures: SettingsExperimentalFeatures = {
isInitialized: true,
searchQueryInput: 'v2',
newSearchResultFiltersPanel: true,
newCodyWeb: true,
}
/**

View File

@ -96,6 +96,11 @@ export interface TemporarySettingsSchema {
/** OpenCodeGraph */
'openCodeGraph.annotations.visible': boolean
'webNext.welcomeOverlay.dismissed': boolean
'webNext.welcomeOverlay.show': boolean
'webNext.departureMessage.dismissed': boolean
'webNext.departureMessage.show': boolean
}
/**
@ -161,6 +166,10 @@ const TEMPORARY_SETTINGS: Record<keyof TemporarySettings, null> = {
'simple.search.toggle': null,
'cody.onboarding.completed': null,
'openCodeGraph.annotations.visible': null,
'webNext.welcomeOverlay.dismissed': null,
'webNext.welcomeOverlay.show': null,
'webNext.departureMessage.dismissed': null,
'webNext.departureMessage.show': null,
}
export const TEMPORARY_SETTINGS_KEYS = Object.keys(TEMPORARY_SETTINGS) as readonly (keyof TemporarySettings)[]

View File

@ -10,9 +10,7 @@ const decorator: Decorator = story => <div className="p-3 container">{story()}</
const config: Meta = {
title: 'shared/SymbolTag',
parameters: {
chromatic: { disableSnapshots: false },
},
parameters: {},
decorators: [decorator],
}

View File

@ -1,4 +1,3 @@
// NOTE(naman): Remember to add events to allow list: https://docs-legacy.sourcegraph.com/dev/background-information/data-usage-pipeline#allow-list
export const enum EventName {
CODY_CHAT_PAGE_VIEWED = 'web:codyChat:pageViewed',
CODY_CHAT_SUBMIT = 'web:codyChat:submit',

View File

@ -1,6 +1,5 @@
load("@npm//:defs.bzl", "npm_link_all_packages")
load("//dev:defs.bzl", "npm_package", "sass", "ts_project")
load("//client/shared/dev:tools.bzl", "module_style_typings")
load("//dev:defs.bzl", "npm_package", "ts_project")
load("//dev:eslint.bzl", "eslint_config_and_lint_root")
# gazelle:js_resolve **/*.module.scss :module_style_typings
@ -25,23 +24,10 @@ ts_config(
],
)
module_style_typings(
name = "module_style_typings",
)
sass(
name = "module_styles",
srcs = glob(["src/**/*.module.scss"]),
)
ts_project(
name = "storybook_lib",
srcs = [
"globals.d.ts",
"src/decorators/withChromaticThemes/ChromaticRoot/ChromaticRoot.tsx",
"src/decorators/withChromaticThemes/ChromaticRoot/index.ts",
"src/decorators/withChromaticThemes/index.ts",
"src/decorators/withChromaticThemes/withChromaticThemes.tsx",
"src/dummyEventSourcePolyfill.ts",
"src/environment-config.ts",
"src/main.ts",
@ -50,7 +36,6 @@ ts_project(
],
tsconfig = ":tsconfig",
deps = [
":module_style_typings",
":node_modules/@sourcegraph/build-config",
":node_modules/@sourcegraph/wildcard",
"//:node_modules/@storybook/addon-actions",
@ -60,14 +45,11 @@ ts_project(
"//:node_modules/@storybook/react-vite",
"//:node_modules/@storybook/theming",
"//:node_modules/@storybook/types",
"//:node_modules/@types/classnames",
"//:node_modules/@types/node",
"//:node_modules/@types/react",
"//:node_modules/classnames",
"//:node_modules/focus-visible",
"//:node_modules/open-color",
"//:node_modules/react",
"//:node_modules/vite-plugin-turbosnap",
],
)
@ -75,7 +57,6 @@ npm_package(
name = "storybook_pkg",
srcs = [
"package.json",
":module_styles", #keep
":storybook_lib",
],
)

View File

@ -9,7 +9,6 @@
"scripts": {
"lint:js": "eslint --cache 'src/**/*.[jt]s?(x)'",
"start": "TS_NODE_TRANSPILE_ONLY=true sb dev -p 9001 -c ./src",
"start:chromatic": "CHROMATIC=true TS_NODE_TRANSPILE_ONLY=true sb dev -p 9001 -c ./src",
"build": "TS_NODE_TRANSPILE_ONLY=true sb build -c ./src",
"test": "echo no tests"
},

View File

@ -1,7 +0,0 @@
.theme-wrapper {
padding: 1rem;
color: var(--body-color);
background-color: var(--body-bg);
position: relative;
min-height: 50vh;
}

View File

@ -1,30 +0,0 @@
import { type FunctionComponent, type PropsWithChildren, useState } from 'react'
import classNames from 'classnames'
import { PopoverRoot } from '@sourcegraph/wildcard'
import { ChromaticThemeContext, type ChromaticTheme } from '@sourcegraph/wildcard/src/stories'
import styles from './ChromaticRoot.module.scss'
interface ChromaticRootProps extends ChromaticTheme {}
export const ChromaticRoot: FunctionComponent<PropsWithChildren<ChromaticRootProps>> = props => {
const { theme, children } = props
const [rootReference, setElement] = useState<HTMLDivElement | null>(null)
const themeClass = theme === 'light' ? 'theme-light' : 'theme-dark'
return (
<ChromaticThemeContext.Provider value={{ theme }}>
{/* Required to render `Popover` inside of the `ChromaticRoot` component. */}
<PopoverRoot.Provider value={{ renderRoot: rootReference }}>
<div className={classNames(themeClass, styles.themeWrapper)}>
{children}
<div ref={setElement} />
</div>
</PopoverRoot.Provider>
</ChromaticThemeContext.Provider>
)
}

View File

@ -1 +0,0 @@
export * from './ChromaticRoot'

View File

@ -1 +0,0 @@
export * from './withChromaticThemes'

View File

@ -1,32 +0,0 @@
import type { ReactElement } from 'react'
import type { Decorator } from '@storybook/react'
import { ChromaticRoot } from './ChromaticRoot'
/**
* The global Storybook decorator used to snapshot stories with multiple themes in Chromatic.
*
* It's a recommended way of achieving this goal:
* https://www.chromatic.com/docs/faq#do-you-support-taking-snapshots-of-a-component-with-multiple-the
*
* If the `chromatic.enableDarkMode` story parameter is set to `true`, the story will
* be rendered twice in Chromatic in light and dark modes.
*/
export const withChromaticThemes: Decorator<ReactElement> = (StoryFunc, { parameters }) => {
if (parameters?.chromatic?.enableDarkMode) {
return (
<>
<ChromaticRoot theme="light">
<StoryFunc />
</ChromaticRoot>
<ChromaticRoot theme="dark">
<StoryFunc />
</ChromaticRoot>
</>
)
}
return <StoryFunc />
}

View File

@ -1,6 +1,3 @@
import { getEnvironmentBoolean } from '@sourcegraph/build-config'
export const ENVIRONMENT_CONFIG = {
STORIES_GLOB: process.env.STORIES_GLOB,
CHROMATIC: getEnvironmentBoolean('CHROMATIC'),
}

View File

@ -3,9 +3,8 @@ import path from 'path'
import type { StorybookConfigVite } from '@storybook/builder-vite'
import type { StorybookConfig as ReactViteStorybookConfig } from '@storybook/react-vite'
import type { StorybookConfig } from '@storybook/types'
import turbosnap from 'vite-plugin-turbosnap'
import { ROOT_PATH, STATIC_ASSETS_PATH, getEnvironmentBoolean } from '@sourcegraph/build-config'
import { ROOT_PATH, STATIC_ASSETS_PATH } from '@sourcegraph/build-config'
import { ENVIRONMENT_CONFIG } from './environment-config'
@ -26,12 +25,7 @@ const getStoriesGlob = (): string[] => {
}
const config: StorybookConfig & StorybookConfigVite & ReactViteStorybookConfig = {
// TODO: This has to be an object and not a string for now due to a bug in Chromatic
// that would cause the builder to not be identified correctly.
framework: {
name: '@storybook/react-vite',
options: {},
},
framework: '@storybook/react-vite',
staticDirs: [path.resolve(__dirname, '../assets'), STATIC_ASSETS_PATH],
stories: getStoriesGlob(),
@ -56,15 +50,6 @@ const config: StorybookConfig & StorybookConfigVite & ReactViteStorybookConfig =
},
viteFinal: (config, { configType }) => {
const isChromatic = getEnvironmentBoolean('CHROMATIC')
config.define = { ...config.define, 'process.env.CHROMATIC': isChromatic }
if (isChromatic && configType === 'PRODUCTION') {
// eslint-disable-next-line no-console
console.log('Using TurboSnap plugin!')
config.plugins = config.plugins ?? []
config.plugins.push(turbosnap({ rootDir: config.root ?? ROOT_PATH }))
}
config.build = {
...config.build,
minify: false,
@ -114,23 +99,4 @@ const config: StorybookConfig & StorybookConfigVite & ReactViteStorybookConfig =
},
}
// TODO: We need to replace the @storybook/addon-storysource plugin with an object
// definition to supply options here because chromatic CLI does not properly understand
// the configured addons otherwise.
const idx = config.addons?.findIndex(addon => addon === '@storybook/addon-storysource')
if (idx !== undefined && idx >= 0) {
config.addons![idx] = {
name: '@storybook/addon-storysource',
options: {
rule: {
test: /\.story\.tsx?$/,
},
sourceLoaderOptions: {
injectStoryParameters: false,
prettierConfig: { printWidth: 80, singleQuote: false },
},
},
}
}
module.exports = config

View File

@ -7,14 +7,12 @@ import { withConsole } from '@storybook/addon-console'
import type { DecoratorFn, Parameters } from '@storybook/react'
import { setLinkComponent, AnchorLink } from '@sourcegraph/wildcard'
import { isChromatic } from '@sourcegraph/wildcard/src/stories'
import { withChromaticThemes } from './decorators/withChromaticThemes'
import { themeDark, themeLight, THEME_DARK_CLASS, THEME_LIGHT_CLASS } from './themes'
const withConsoleDecorator: DecoratorFn = (storyFunc, context): ReactElement => withConsole()(storyFunc)(context)
export const decorators = [withConsoleDecorator, isChromatic() && withChromaticThemes].filter(Boolean)
export const decorators = [withConsoleDecorator].filter(Boolean)
export const parameters: Parameters = {
layout: 'fullscreen',
@ -31,36 +29,12 @@ export const parameters: Parameters = {
light: themeLight,
dark: themeDark,
},
// disables snapshotting for all stories by default
chromatic: { disableSnapshot: true },
}
configureActions({ depth: 100, limit: 20 })
setLinkComponent(AnchorLink)
// Default to light theme for Chromatic and "Open canvas in new tab" button.
// addon-dark-mode will override this if it's running.
if (!document.body.classList.contains('theme-dark')) {
document.body.classList.add('theme-light')
}
// Default to light theme for Chromatic and "Open canvas in new tab" button.
// addon-dark-mode will override this if it's running.
if (!document.body.classList.contains('theme-dark')) {
document.body.classList.add('theme-light')
}
if (isChromatic()) {
const style = document.createElement('style')
style.innerHTML = `
.monaco-editor .cursor {
visibility: hidden !important;
}
`
document.head.append(style)
}
declare global {
interface Window {
STORYBOOK_ENV?: string

View File

@ -2,7 +2,6 @@ import ResizeObserver from 'resize-observer-polyfill'
import { vi } from 'vitest'
if ('ResizeObserver' in window === false) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
window.ResizeObserver = ResizeObserver
}

View File

@ -13,9 +13,7 @@ Apache
## Feedback
Your feedback is important to us and is greatly appreciated. Please do not hesitate to submit your ideas or suggestions
about how we can improve the extension to
our [VS Code Extension Feedback Discussion Thread](https://github.com/sourcegraph/sourcegraph/discussions/34821) on
GitHub.
about how we can improve the extension to our [Code Search discussion community](https://community.sourcegraph.com/c/code-search/9).
## Issues / Bugs
@ -196,7 +194,7 @@ with us on the [Sourcegraph Community Slack group](https://about.sourcegraph.com
- [Code of Conduct](https://handbook.sourcegraph.com/company-info-and-process/community/code_of_conduct/)
- [Developing Sourcegraph guide](https://docs.sourcegraph.com/dev)
- [Developing the web clients](https://docs.sourcegraph.com/dev/background-information/web)
- [Feedback / Feature Request](https://github.com/sourcegraph/sourcegraph/discussions/34821)
- [Feedback / Feature Request](https://community.sourcegraph.com/c/code-search/9)
- [Issue Tracker](https://github.com/sourcegraph/sourcegraph/labels/vscode-extension)
- [Report a bug](https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board)
- [Troubleshooting docs](https://docs.sourcegraph.com/admin/how-to/troubleshoot-sg-extension#vs-code-extension)

View File

@ -118,9 +118,7 @@ This extension contributes the following settings:
## Questions & Feedback
Feedback and feature requests can be submitted to
our [VS Code Extension Feedback Discussion Board](https://github.com/sourcegraph/sourcegraph/discussions/34821) on
GitHub.
Feedback and feature requests can be submitted to our [Code Search discussion community](https://community.sourcegraph.com/c/code-search/9).
## Uninstallation

View File

@ -28,7 +28,6 @@ const currentAuthStateQuery = gql`
nodes {
id
name
displayName
url
settingsURL
}

View File

@ -7,6 +7,7 @@ import { requestGraphQLFromVSCode } from './requestGraphQl'
const blobContentQuery = gql`
query BlobContent($repository: String!, $revision: String!, $path: String!) {
repository(name: $repository) {
id
commit(rev: $revision) {
blob(path: $path) {
content

View File

@ -34,7 +34,7 @@ const VSCE_LINK_PARAMS_UTM_SIDEBAR = {
export const VSCE_LINK_MARKETPLACE = 'https://marketplace.visualstudio.com/items?itemName=sourcegraph.sourcegraph'
export const VSCE_LINK_USER_DOCS =
'https://docs.sourcegraph.com/cli/how-tos/creating_an_access_token' + VSCE_SIDEBAR_PARAMS
export const VSCE_LINK_FEEDBACK = 'https://github.com/sourcegraph/sourcegraph/discussions/categories/feedback'
export const VSCE_LINK_FEEDBACK = 'https://community.sourcegraph.com'
export const VSCE_LINK_ISSUES =
'https://github.com/sourcegraph/sourcegraph/issues/new?labels=team/integrations,vscode-extension&title=VSCode+Bug+report:+&projects=Integrations%20Project%20Board'
export const VSCE_LINK_TROUBLESHOOT =

View File

@ -1,5 +0,0 @@
PUBLIC_DOTCOM=
PUBLIC_CODY_ENABLED_ON_INSTANCE=true
PUBLIC_CODY_ENABLED_FOR_CURRENT_USER=true
PUBLIC_BATCH_CHANGES_ENABLED=true
PUBLIC_CODE_INSIGHTS_ENABLED=true

View File

@ -1,5 +0,0 @@
PUBLIC_DOTCOM=true
PUBLIC_CODY_ENABLED_ON_INSTANCE=true
PUBLIC_CODY_ENABLED_FOR_CURRENT_USER=true
PUBLIC_BATCH_CHANGES_ENABLED=
PUBLIC_CODE_INSIGHTS_ENABLED=

View File

@ -1,7 +1,10 @@
import type { Preview } from '@storybook/svelte'
import { initialize, mswLoader } from 'msw-storybook-addon'
// Global imports kept in sync with routes/+layout.svelte
import '../src/routes/styles.scss'
import '@fontsource-variable/roboto-mono'
import '@fontsource-variable/inter'
// Initialize MSW
initialize()

View File

@ -18,8 +18,6 @@ SRCS = [
".eslintignore",
".eslintrc.cjs",
".prettierignore",
".env",
".env.dotcom",
"//client/wildcard:sass-breakpoints",
"//client/wildcard:global-style-sources",
"//client/web/dist/img:copy",
@ -99,24 +97,20 @@ BUILD_DEPS = [
":node_modules/@sentry/sveltekit",
":node_modules/@sourcegraph/branded",
":node_modules/@sourcegraph/client-api",
":node_modules/@sourcegraph/cody-web",
":node_modules/@sourcegraph/common",
":node_modules/@sourcegraph/http-client",
":node_modules/@sourcegraph/shared",
":node_modules/@sourcegraph/telemetry",
":node_modules/@sourcegraph/web",
":node_modules/@sourcegraph/wildcard",
":node_modules/@storybook/svelte",
":node_modules/@sveltejs/adapter-static",
":node_modules/@sveltejs/kit",
":node_modules/@sveltejs/vite-plugin-svelte",
":node_modules/@types/prismjs",
":node_modules/@urql/core",
":node_modules/cody-web-experimental",
":node_modules/fzf",
":node_modules/graphql",
":node_modules/hotkeys-js",
":node_modules/mermaid",
":node_modules/prismjs",
":node_modules/re2js",
":node_modules/sass",
":node_modules/signale",
@ -198,19 +192,21 @@ copy_to_directory(
playwright_test_bin.playwright_test(
name = "e2e_test",
timeout = "short",
timeout = "long",
args = [
"test",
"--config $(location playwright.config.ts)",
],
data = glob(
[
"src/**/*.spec.ts",
"src/**/*.ts",
"src/testing/*.ts",
],
) + [
"playwright.config.ts",
"tsconfig.json",
":generate-graphql-types",
":sveltekit-sync",
":test_app_assets",
"//cmd/frontend/graphqlbackend:graphql_schema",
"//dev/tools:chromium",
@ -220,7 +216,6 @@ playwright_test_bin.playwright_test(
"BAZEL": "1",
"ASSETS_DIR": "./client/web-sveltekit/test_app_assets/test_build/_sk/",
},
flaky = True,
)
TESTS = glob([
@ -249,7 +244,9 @@ vitest_test(
bin = vitest_bin,
chdir = package_name(),
data = SRCS + BUILD_DEPS + CONFIGS + TESTS + TEST_BUILD_DEPS,
tags = [TAG_SEARCHSUITE],
tags = [
TAG_SEARCHSUITE,
],
with_vitest_config = False,
)
@ -333,10 +330,10 @@ svelte_check.svelte_check_test(
args = [
"--tsconfig",
"tsconfig.json",
"--compiler-warnings",
# missing-declaration is raised for our icon components. The Svelte compiler
# does not take into account ambient declarations (will be fixed in Svelte 5).
"missing-declaration:ignore",
# This causes only errors to be displayed, which is what we want
# to keep noise down in CI
"--threshold",
"error",
],
chdir = package_name(),
data = SRCS + BUILD_DEPS + CONFIGS + [
@ -347,6 +344,11 @@ svelte_check.svelte_check_test(
# Needed to properly extend vite's UserConfig type
":node_modules/vitest",
],
env = {
# It appears that svelte-check will start the vite dev server,
# but in this case we don't want the proxy to be enabled.
"SK_DISABLE_PROXY": "1",
},
)
filegroup(

View File

@ -3,28 +3,51 @@
This folder contains the experimental [SvelteKit](https://kit.svelte.dev/)
implementation of the Sourcegraph app.
**NOTE:** This is a _very early_ prototype and it will change a lot.
## Developing
```bash
# Install dependencies
pnpm install
# Run dev server
pnpm run dev
```
There are multiple ways to start the app:
The dev server can be accessed on http://localhost:5173. API requests and
signin/signout are proxied to an actual Sourcegraph instance,
https://sourcegraph.com by default (can be overwritten via the
`SOURCEGRAPH_API_URL` environment variable.
If you're a Sourcegraph employee you should run this command to use the right auth instance:
1. Standalone and proxying to S2
```bash
SOURCEGRAPH_API_URL=https://sourcegraph.sourcegraph.com pnpm run dev
cd client/web-sveltekit
pnpm dev
```
Then go to (usually) http://localhost:5173.
Or via `sg`:
```bash
sg start web-sveltekit-standalone
```
Then go to https://sourcegraph.test:5173.
2. Standalone and proxying to dotcom
```bash
cd client/web-sveltekit
pnpm dev:dotcom
```
3. Standalone and proxying to another Sourcegraph instance
```bash
cd client/web-sveltekit
SOURCEGRAPH_API_URL=https://<instance> pnpm dev
```
Then go to (usually) http://localhost:5173.
3. Against a local Sourcegraph instance
```bash
sg start enterprise-sveltekit
```
Then go to https://sourcegraph.test:5173.
### Using code from `@sourcegraph/*`
There are some things to consider when using code from other `@sourcegraph`
@ -59,7 +82,20 @@ pnpm vitest # Run vitest tests
pnpm test # Run playwright tests
```
In CI we run vitest tests. Playwright test support is currently being worked on.
You can also run playwright tests against a running vite dev server. This is
useful for debugging tests.
```sh
# In one terminal
pnpm dev
```
```sh
# In another terminal
pnpm test:dev
```
Both vitest and playwright tests are run in CI.
### Formatting and linting
@ -87,6 +123,34 @@ This noise can be avoided by running the corresponding bazel command instead:
bazel test //client/web-sveltekit:svelte-check
```
### Icons
We use [unplugin-icons](https://github.com/unplugin/unplugin-icons) together
with [unplugin-auto-import](https://github.com/unplugin/unplugin-auto-import)
to manage icons. This allows us to use icons from multiple icon sets without
having to import them manually.
For a list of currently available icon sets see the `@iconify-json/*` packages
in the `package.json` file.
Icon references have the form `I<IconSetName><IconName>`. For example the
[corner down left arrow from Lucide](https://lucide.dev/icons/corner-down-left)
can be referenced as `ILucideCornerDownLeft`.
The icon reference is then used in the `Icon` component. Note that the icon
doesn't have to be imported manually.
```svelte
<script lang="ts">
import { Icon } from '$lib/Icon.svelte';
</script>
<Icon icon={ILucideCornerDownLeft} />
```
When the development server is running, the icon will be automatically added to
`auto-imports.d.ts` so TypeScript knows about it.
### Data loading with GraphQL
This project makes use of query composition, i.e. components define their own

View File

@ -0,0 +1,15 @@
<svg viewBox="0 0 52 52" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M30.8 51.8c-2.8.5-5.5-1.3-6-4.1L17.2 6.2c-.5-2.8 1.3-5.5 4.1-6s5.5 1.3 6 4.1l7.6 41.5c.5 2.8-1.4 5.5-4.1 6z"
fill="var(--icon-color, #FF5543)"
/>
<path
d="M10.9 44.7C9.1 45 7.3 44.4 6 43c-1.8-2.2-1.6-5.4.6-7.2L38.7 8.5c2.2-1.8 5.4-1.6 7.2.6 1.8 2.2 1.6 5.4-.6 7.2l-32 27.3c-.7.6-1.6 1-2.4 1.1z"
fill="var(--icon-color, #A112FF)"
/>
<path
d="M46.8 38.1c-.9.2-1.8.1-2.6-.2L4.4 23.8c-2.7-1-4.1-3.9-3.1-6.6 1-2.7 3.9-4.1 6.6-3.1l39.7 14.1c2.7 1 4.1 3.9 3.1 6.6-.6 1.8-2.2 3-3.9 3.3z"
fill="var(--icon-color, #00CBEC)"
/>
</svg>

After

Width:  |  Height:  |  Size: 679 B

View File

@ -0,0 +1,13 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g id=".Icon / Symbols" clip-path="url(#clip0_4465_142348)">
<path id="Vector" d="M1.75 0.75H8.75C8.75 0.75 9.75 0.75 9.75 1.75V8.75C9.75 8.75 9.75 9.75 8.75 9.75H1.75C1.75 9.75 0.75 9.75 0.75 8.75V1.75C0.75 1.75 0.75 0.75 1.75 0.75Z" stroke="var(--icon-color)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<path id="Vector_2" d="M14.25 5.25C14.25 5.84095 14.3664 6.42611 14.5925 6.97208C14.8187 7.51804 15.1502 8.01412 15.568 8.43198C15.9859 8.84984 16.482 9.18131 17.0279 9.40746C17.5739 9.6336 18.1591 9.75 18.75 9.75C19.3409 9.75 19.9261 9.6336 20.4721 9.40746C21.018 9.18131 21.5141 8.84984 21.932 8.43198C22.3498 8.01412 22.6813 7.51804 22.9075 6.97208C23.1336 6.42611 23.25 5.84095 23.25 5.25C23.25 4.65905 23.1336 4.07389 22.9075 3.52792C22.6813 2.98196 22.3498 2.48588 21.932 2.06802C21.5141 1.65016 21.018 1.31869 20.4721 1.09254C19.9261 0.866396 19.3409 0.75 18.75 0.75C18.1591 0.75 17.5739 0.866396 17.0279 1.09254C16.482 1.31869 15.9859 1.65016 15.568 2.06802C15.1502 2.48588 14.8187 2.98196 14.5925 3.52792C14.3664 4.07389 14.25 4.65905 14.25 5.25Z" stroke="var(--icon-color)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<path id="Vector_3" d="M18.7859 13.9771C18.7111 13.8333 18.5982 13.7127 18.4596 13.6286C18.321 13.5445 18.162 13.5 17.9999 13.5C17.8378 13.5 17.6787 13.5445 17.5401 13.6286C17.4016 13.7127 17.2887 13.8333 17.2139 13.9771L12.8769 21.7841C12.7948 21.9334 12.7512 22.1008 12.75 22.2712C12.7488 22.4416 12.79 22.6096 12.8699 22.7601C12.9452 22.906 13.0587 23.0287 13.1984 23.1151C13.3381 23.2014 13.4987 23.2481 13.6629 23.2501H22.3369C22.5011 23.2481 22.6616 23.2014 22.8013 23.1151C22.941 23.0287 23.0546 22.906 23.1299 22.7601C23.2098 22.6096 23.251 22.4416 23.2497 22.2712C23.2485 22.1008 23.2049 21.9334 23.1229 21.7841L18.7859 13.9771Z" stroke="var(--icon-color)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
<path id="Vector_4" d="M5.85108 13.0347C5.77808 12.9463 5.68644 12.8751 5.58272 12.8262C5.47899 12.7773 5.36574 12.752 5.25108 12.752C5.13641 12.752 5.02316 12.7773 4.91944 12.8262C4.81571 12.8751 4.72407 12.9463 4.65108 13.0347L0.941077 17.4717C0.817448 17.6203 0.749756 17.8074 0.749756 18.0007C0.749756 18.194 0.817448 18.3811 0.941077 18.5297L4.64908 22.9667C4.72207 23.0551 4.81371 23.1263 4.91744 23.1752C5.02116 23.2241 5.13441 23.2494 5.24908 23.2494C5.36374 23.2494 5.47699 23.2241 5.58072 23.1752C5.68444 23.1263 5.77608 23.0551 5.84908 22.9667L9.55708 18.5297C9.68071 18.3811 9.7484 18.194 9.7484 18.0007C9.7484 17.8074 9.68071 17.6203 9.55708 17.4717L5.85108 13.0347Z" stroke="var(--icon-color)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
</g>
<defs>
<clipPath id="clip0_4465_142348">
<rect width="24" height="24" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

@ -0,0 +1,276 @@
import type { IncomingMessage } from 'http'
import { Transform } from 'stream'
import { createLogger, type Plugin, type ProxyOptions } from 'vite'
import { svelteKitRoutes, type SvelteKitRoute } from '../src/lib/routes'
interface Options {
target: string
}
/**
* This plugin proxies certain requests to a real Sourcegraph instance. These include
* - API and auth requests
* - asset requests for the React app
* - requests for pages that are not known by the SvelteKit app (e.g. code insights)
*
* It does this by first fetching the sign-in page from the real Sourcegraph instance
* and extracting the JS context object from it. This object contains a list of
* routes known by the server, some of which will be handled by the SvelteKit app.
* (the other data in JS context is ignored)
* Those that are not will be proxied to the real Sourcegraph instance.
*
* Additionally, the plugin injects the JS context provided by the origin server into
* locally generated HTML pages.
*
* This plugin is only enabled in 'serve' mode.
*/
export function sgProxy(options: Options): Plugin {
const name = 'sg:proxy'
const logger = createLogger(undefined, { prefix: `[${name}]` })
// Needs to be kept in sync with app.html
const contextPlaceholder = '// ---window.context---'
// Additional endpoints that should be proxied to the real Sourcegraph instance.
const additionalEndpoints = [
// These are not part of the known routes list, but are required for the SvelteKit app to work
// in development mode.
'^/.api/',
'^/.assets/',
'^/.auth/',
// Repo sub pages are also not part of the known routes list. They are listed here so that we
// proxy them to the real Sourcegraph instance, for consistency with the production setup.
'/-/raw/',
'/-/batch-changes/?',
'/-/settings/?',
'/-/code-graph/?',
'/-/own/?',
]
// Routes known by the server that need to (potentially) be proxied to the real Sourcegraph instance.
let knownServerRoutes: string[] = []
function extractContextRaw(body: string): string | null {
const match = body.match(/window\.context\s*=\s*{.*}/)
return match?.[0] ?? null
}
function extractContext(body: string): Window['context'] | null {
const context = extractContextRaw(body)
if (!context) {
return null
}
return new Function(`return ${context.match(/\{.*\}/)?.[0] ?? ''}`)()
}
/**
* Returns true if the request should be handled by the SvelteKit app. This uses similar
* logic to the `isRouteEnabled` function in the SvelteKit app.
* If the request
*/
function isHandledBySvelteKit(req: IncomingMessage, knownRoutes: string[]) {
const url = new URL(req.url ?? '', `http://${req.headers.host}`)
let foundRoute: SvelteKitRoute | undefined
for (const route of svelteKitRoutes) {
if (route.pattern.test(url.pathname)) {
foundRoute = route
if (!route.isRepoRoot) {
break
}
}
}
if (foundRoute) {
return foundRoute.isRepoRoot ? !knownRoutes.some(route => new RegExp(route).test(url.pathname)) : true
}
return false
}
return {
name,
apply: 'serve',
async config() {
if (!options.target) {
logger.info('No target specified, not proxying requests', { timestamp: true })
return
}
let context: Window['context'] | null
// At startup we fetch the sign-in page from the real Sourcegraph instance to extract the `knownRoutes` array
// from the JS context object. This is used to determine which requests should be proxied to the real Sourcegraph
// instance.
// We keep trying to connect to the origin server in case it is not yet available (e.g. when just starting up a
// local Sourcegraph instance).
let backoff = 1
while (true) {
try {
logger.info(`Fetching JS context from ${options.target}`, { timestamp: true })
// The /sign-in endpoint is always available on dotcom and enterprise instances.
context = await fetch(`${options.target}/sign-in`)
.then(response => response.text())
.then(extractContext)
break
} catch (error) {
logger.error(`Failed to fetch JS context: ${(error as Error).message}`, { timestamp: true })
logger.info(`Retrying in ${backoff} second(s)...`, { timestamp: true })
await new Promise(resolve => setTimeout(resolve, backoff * 1000))
backoff = Math.min(backoff * 2, 10)
}
}
if (!context) {
logger.error('Failed to extract JS context from origin', { timestamp: true })
return
}
knownServerRoutes = context.svelteKit?.knownRoutes ?? []
if (!knownServerRoutes.length) {
logger.error('Failed to extract known routes from JS context', { timestamp: true })
return
}
logger.info(`Known routes from origin JS context\n - ${knownServerRoutes.join('\n - ')}\n`, {
timestamp: true,
})
const baseOptions: ProxyOptions = {
target: options.target,
changeOrigin: true,
secure: false,
headers: context.xhrHeaders,
}
const proxyConfig: Record<string, ProxyOptions> = {
// Proxy requests to specific endpoints to a real Sourcegraph instance.
[`${additionalEndpoints.join('|')}`]: baseOptions,
}
const dynamicOptions: ProxyOptions = {
bypass(req) {
if (!req.url) {
return null
}
// If the request is for a SvelteKit route, we want to serve the SvelteKit app.
return isHandledBySvelteKit(req, knownServerRoutes) ? req.url : null
},
...baseOptions,
}
for (const route of knownServerRoutes) {
// vite's proxy server matches full URL, including query parameters.
// That means a route regex like `^/search[/]?$` (which the server provides)
// would not match `/search?q=foo`. We extend every route regex to allow
// for any query parameters
proxyConfig[route.replace(/\$$/, '(\\?.*)?$')] = dynamicOptions
}
return {
server: {
proxy: proxyConfig,
},
}
},
configureServer(server) {
if (!options.target) {
return
}
server.middlewares.use(function proxyHTML(req, res, next) {
// When a request is made for an HTML page that is handled by the SvelteKit
// we want to inject the same JS context object that we would have fetched
// from the origin server.
// The implementation is quite hacky but apparently but it seems there is no
// better way to do this. It was inspired by the express compression middleware:
// https://github.com/expressjs/compression/blob/f3e6f389cb87e090438e13c04d67cec9e22f8098/index.js
if (req.headers.accept?.includes('html') && isHandledBySvelteKit(req, knownServerRoutes)) {
const setHeader = res.setHeader
const write = res.write
const on = res.on
const end = res.end
const context = fetch(`${options.target}${req.url}`, {
headers: req.headers.cookie ? { cookie: req.headers.cookie } : {},
})
.then(response => response.text())
.then(body => {
const context = extractContextRaw(body)
if (!context) {
throw new Error('window.context not found in response from origin')
}
return context
})
const transform = new Transform({
transform(chunk, encoding, callback) {
context
.then(context => {
let body = Buffer.from(chunk).toString()
if (body.includes(contextPlaceholder)) {
body = body.replace(contextPlaceholder, context)
logger.info(`${req.url} - injected JS context`, { timestamp: true })
}
callback(null, body)
})
.catch(error => {
logger.error(`Error fetching JS context: ${error.message}`, { timestamp: true })
// We explicitly pass null to not cause the proxy to terminate
callback(null, chunk)
})
},
})
transform
.on('data', chunk => {
// @ts-expect-error - the overload signature of write seems to prevent TS from recognizing the correct arguments
if (write.call(res, chunk) === false) {
transform.pause()
}
})
.on('end', () => {
// @ts-expect-error - the overload signature of end seems to prevent TS from recognizing the correct arguments
end.call(res)
})
res.on('drain', () => transform.resume())
let ended = false
res.setHeader = (name, value) => {
// content-length is set and sent before we have a chance to modify the response
// we need to ignore it, otherwise the browser will not render the page
// properly
return name === 'content-length' ? res : setHeader.call(res, name, value)
}
// @ts-expect-error - the overload signature of write seems to prevent TS from recognizing the correct arguments
res.write = (chunk, encoding, cb) => {
if (ended) {
return false
}
return transform.write(chunk, encoding, cb)
}
// @ts-expect-error - the overload signature of write seems to prevent TS from recognizing the correct arguments
res.end = (chunk, encoding, cb) => {
if (ended) {
return false
}
ended = true
return transform.end(chunk, encoding, cb)
}
// @ts-expect-error - the overload signature of write seems to prevent TS from recognizing the correct arguments
res.on = (type, listener) => {
if (type === 'drain') {
return transform.on(type, listener)
}
return on.call(res, type, listener)
}
}
next()
})
},
}
}

View File

@ -8,14 +8,15 @@
"build": "vite build",
"build:preview": "vite build --mode=preview",
"build:watch": "vite build --watch",
"build:enterprise": "DEPLOY_TYPE=dev vite build",
"preview": "vite preview",
"install:browsers": "playwright install",
"test": "DISABLE_APP_ASSETS_MOCKING=true playwright test",
"test:dev": "DISABLE_APP_ASSETS_MOCKING=true PORT=5173 playwright test --ui",
"test:svelte": "vitest --run",
"sync": "svelte-kit sync",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"check": "SK_DISABLE_PROXY=true svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "SK_DISABLE_PROXY=true svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "eslint .",
"format": "prettier --config ./prettier.config.cjs --write . --plugin prettier-plugin-svelte",
"generate": "pnpm -w generate",
@ -37,15 +38,11 @@
"@iconify-json/mdi": "^1.1.67",
"@iconify-json/ph": "^1.1.13",
"@iconify-json/simple-icons": "^1.1.104",
"@playwright/test": "1.42.1",
"@playwright/test": "1.46.0",
"@storybook/addon-essentials": "^8.0.5",
"@storybook/addon-interactions": "^7.2.0",
"@storybook/addon-links": "^7.2.0",
"@storybook/addon-svelte-csf": "^4.1.2",
"@storybook/blocks": "^8.0.5",
"@storybook/svelte": "^8.0.5",
"@storybook/sveltekit": "^8.0.5",
"@storybook/testing-library": "0.2.0",
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-static": "^3.0.0",
"@sveltejs/kit": "^2.5.17",
@ -54,13 +51,12 @@
"@testing-library/user-event": "^14.4.3",
"@types/cookie": "^0.5.1",
"@types/highlight.js": "^9.12.4",
"@types/prismjs": "^1.26.0",
"eslint-plugin-storybook": "^0.8.0",
"eslint-plugin-svelte3": "^4.0.0",
"graphql": "^15.0.0",
"msw": "^1.2.3",
"msw-storybook-addon": "^1.10.0",
"playwright": "1.42.1",
"playwright": "1.46.0",
"prettier": "2.8.1",
"prettier-plugin-svelte": "^2.0.0",
"sass": "^1.32.4",
@ -85,21 +81,17 @@
"@sentry/sveltekit": "^8.7.0",
"@sourcegraph/branded": "workspace:*",
"@sourcegraph/client-api": "workspace:*",
"@sourcegraph/cody-web": "^0.4.0",
"@sourcegraph/common": "workspace:*",
"@sourcegraph/http-client": "workspace:*",
"@sourcegraph/shared": "workspace:*",
"@sourcegraph/telemetry": "^0.11.0",
"@sourcegraph/web": "workspace:*",
"@sourcegraph/wildcard": "workspace:*",
"@storybook/test": "^8.0.5",
"@urql/core": "^4.2.3",
"cody-web-experimental": "^0.2.4",
"copy-to-clipboard": "^3.3.1",
"fzf": "^0.5.2",
"highlight.js": "^10.0.0",
"hotkeys-js": "^3.13.7",
"mermaid": "^10.9.1",
"prismjs": "^1.29.0",
"re2js": "^0.4.1",
"ts-key-enum": "^2.0.12",
"wonka": "^6.3.4",

View File

@ -11,6 +11,11 @@ const config: PlaywrightTestConfig = {
command: 'pnpm build:preview && pnpm preview',
port: PORT,
reuseExistingServer: true,
env: {
// Disable proxying to a real Sourcegraph instance in local testing
SK_DISABLE_PROXY: 'true',
},
timeout: 5 * 60_000,
}
: undefined,
reporter: 'list',

View File

@ -2,5 +2,8 @@ const baseConfig = require('../../prettier.config.js')
module.exports = {
...baseConfig,
plugins: [...(baseConfig.plugins || []), 'prettier-plugin-svelte'],
overrides: [...(baseConfig.overrides || []), { files: '*.svelte', options: { parser: 'svelte' } }],
overrides: [
...(baseConfig.overrides || []),
{ files: '*.svelte', options: { parser: 'svelte', htmlWhitespaceSensitivity: 'strict' } },
],
}

View File

@ -12,22 +12,21 @@
<meta name="color-scheme" content="light dark" />
<script ignore-csp>
window.context = {
// Necessary to make authenticated GraphQL requests in dev mode
xhrHeaders: {
'X-Requested-With': 'Sourcegraph',
},
// Local standalone dev server for dotcom can be started with
// pnpm dev:dotcom
sourcegraphDotComMode: !!'%sveltekit.env.PUBLIC_DOTCOM%',
codyEnabledOnInstance: !!'%sveltekit.env.PUBLIC_CODY_ENABLED_ON_INSTANCE%',
codyEnabledForCurrentUser: !!'%sveltekit.env.PUBLIC_CODY_ENABLED_FOR_CURRENT_USER%',
batchChangesEnabled: !!'%sveltekit.env.PUBLIC_BATCH_CHANGES_ENABLED%',
codeInsightsEnabled: !!'%sveltekit.env.PUBLIC_CODE_INSIGHTS_ENABLED%',
// The window.context object extracted from the origin server is injected here.
// Needs to be kept in sync with the vite-sg-proxy.ts plugin
// ---window.context---
// The following are used to mock context in playwright tests
...(typeof window.context === 'object' ? window.context : {}),
}
window.context = Object.assign(
{},
// Injected window.context (via proxy) if available
window.context,
// Dev specific overwrites
{
sentryDSN: undefined,
},
// Playwright specific overwrites
window.playwrightContext
)
window.pageError = undefined
</script>

View File

@ -11,6 +11,7 @@ declare global {
const ILucideArchive: typeof import('~icons/lucide/archive')['default']
const ILucideArrowDownFromLine: typeof import('~icons/lucide/arrow-down-from-line')['default']
const ILucideArrowLeftFromLine: typeof import('~icons/lucide/arrow-left-from-line')['default']
const ILucideArrowRight: typeof import('~icons/lucide/arrow-right')['default']
const ILucideArrowRightFromLine: typeof import('~icons/lucide/arrow-right-from-line')['default']
const ILucideBarChartBig: typeof import('~icons/lucide/bar-chart-big')['default']
const ILucideBookOpen: typeof import('~icons/lucide/book-open')['default']
@ -39,9 +40,9 @@ declare global {
const ILucideEllipsis: typeof import('~icons/lucide/ellipsis')['default']
const ILucideExternalLink: typeof import('~icons/lucide/external-link')['default']
const ILucideEye: typeof import('~icons/lucide/eye')['default']
const ILucideFIleText: typeof import('~icons/lucide/f-ile-text')['default']
const ILucideFile: typeof import('~icons/lucide/file')['default']
const ILucideFileCode: typeof import('~icons/lucide/file-code')['default']
const ILucideFileDiff: typeof import('~icons/lucide/file-diff')['default']
const ILucideFileJson: typeof import('~icons/lucide/file-json')['default']
const ILucideFileSearch2: typeof import('~icons/lucide/file-search2')['default']
const ILucideFileStack: typeof import('~icons/lucide/file-stack')['default']
@ -61,12 +62,14 @@ declare global {
const ILucideGitCompareArrows: typeof import('~icons/lucide/git-compare-arrows')['default']
const ILucideGitFork: typeof import('~icons/lucide/git-fork')['default']
const ILucideGitMerge: typeof import('~icons/lucide/git-merge')['default']
const ILucideHelp: typeof import('~icons/lucide/help')['default']
const ILucideHistory: typeof import('~icons/lucide/history')['default']
const ILucideHome: typeof import('~icons/lucide/home')['default']
const ILucideInfo: typeof import('~icons/lucide/info')['default']
const ILucideLink: typeof import('~icons/lucide/link')['default']
const ILucideLock: typeof import('~icons/lucide/lock')['default']
const ILucideMenu: typeof import('~icons/lucide/menu')['default']
const ILucideNetwork: typeof import('~icons/lucide/network')['default']
const ILucideOctagonX: typeof import('~icons/lucide/octagon-x')['default']
const ILucidePanelBottomClose: typeof import('~icons/lucide/panel-bottom-close')['default']
const ILucidePanelLeftClose: typeof import('~icons/lucide/panel-left-close')['default']
@ -74,6 +77,7 @@ declare global {
const ILucidePencil: typeof import('~icons/lucide/pencil')['default']
const ILucideRegex: typeof import('~icons/lucide/regex')['default']
const ILucideRepeat: typeof import('~icons/lucide/repeat')['default']
const ILucideScanSearch: typeof import('~icons/lucide/scan-search')['default']
const ILucideSearch: typeof import('~icons/lucide/search')['default']
const ILucideSearchX: typeof import('~icons/lucide/search-x')['default']
const ILucideSettings: typeof import('~icons/lucide/settings')['default']
@ -81,15 +85,16 @@ declare global {
const ILucideSquareFunction: typeof import('~icons/lucide/square-function')['default']
const ILucideSquareSlash: typeof import('~icons/lucide/square-slash')['default']
const ILucideStar: typeof import('~icons/lucide/star')['default']
const ILucideSymbols: typeof import('~icons/lucide/symbols')['default']
const ILucideTag: typeof import('~icons/lucide/tag')['default']
const ILucideText: typeof import('~icons/lucide/text')['default']
const ILucideUser: typeof import('~icons/lucide/user')['default']
const ILucideUsers: typeof import('~icons/lucide/users')['default']
const ILucideWrapText: typeof import('~icons/lucide/wrap-text')['default']
const ILucideX: typeof import('~icons/lucide/x')['default']
const ILucidehevronLeft: typeof import('~icons/lucide/hevron-left')['default']
const IMdiFormatLetterCase: typeof import('~icons/mdi/format-letter-case')['default']
const IMdiRegex: typeof import('~icons/mdi/regex')['default']
const IMdiTools: typeof import('~icons/mdi/tools')['default']
const IPhFileJpgLight: typeof import('~icons/ph/file-jpg-light')['default']
const IPhFilePngLight: typeof import('~icons/ph/file-png-light')['default']
const IPhGifFill: typeof import('~icons/ph/gif-fill')['default']
@ -100,6 +105,8 @@ declare global {
const IPhosphorePngLight: typeof import('~icons/ph/osphore-png-light')['default']
const ISgBatchChanges: typeof import('~icons/sg/batch-changes')['default']
const ISgCody: typeof import('~icons/sg/cody')['default']
const ISgMark: typeof import('~icons/sg/mark')['default']
const ISgSymbols: typeof import('~icons/sg/symbols')['default']
const ISimpleIconsApachegroovy: typeof import('~icons/simple-icons/apachegroovy')['default']
const ISimpleIconsBitbucket: typeof import('~icons/simple-icons/bitbucket')['default']
const ISimpleIconsC: typeof import('~icons/simple-icons/c')['default']

View File

@ -32,14 +32,13 @@
{#if avatarURL}
<img src={avatarURL} role="presentation" aria-hidden="true" alt="Avatar of {name}" data-avatar />
{:else}
<div data-avatar>
<div data-avatar title={name}>
<span>{getInitials(name)}</span>
</div>
{/if}
<style lang="scss">
span {
z-index: 1;
color: var(--text-muted);
font-size: calc(var(--size) * 0.5);
font-weight: 500;
@ -50,29 +49,21 @@
--min-size: 1.25rem;
--size: var(--avatar-size, var(--icon-inline-size, var(--min-size)));
flex: none;
min-width: var(--min-size);
min-height: var(--min-size);
width: var(--size);
height: var(--size);
isolation: isolate;
display: inline-flex;
border-radius: 50%;
text-transform: capitalize;
color: var(--color-bg-1);
display: inline-flex;
align-items: center;
justify-content: center;
position: relative;
background: var(--secondary);
flex: none;
}
div::after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
border-radius: 50%;
text-transform: capitalize;
color: var(--color-bg-1);
background: var(--secondary);
user-select: none;
}
</style>

View File

@ -0,0 +1,29 @@
fragment Changelist on PerforceChangelist {
cid
canonicalURL
commit {
message
oid
body
subject
author {
person {
...Avatar_Person
}
date
}
parents {
id
oid
abbreviatedOID
parent: perforceChangelist {
cid
canonicalURL
}
}
perforceChangelist {
cid
canonicalURL
}
}
}

View File

@ -0,0 +1,157 @@
<svelte:options immutable />
<script lang="ts">
import Avatar from '$lib/Avatar.svelte'
import Icon from '$lib/Icon.svelte'
import Timestamp from '$lib/Timestamp.svelte'
import Tooltip from '$lib/Tooltip.svelte'
import type { Changelist } from './Changelist.gql'
import { isViewportMobile } from './stores'
import Button from './wildcard/Button.svelte'
export let changelist: Changelist
export let alwaysExpanded: boolean = false
$: expanded = alwaysExpanded
$: author = changelist.commit.author
$: commitDate = new Date(author.date)
$: authorAvatarTooltip = author.person.name + (author ? ' (author)' : '')
</script>
<div class="root">
<div class="avatar">
<Tooltip tooltip={authorAvatarTooltip}>
<Avatar avatar={author.person} />
</Tooltip>
</div>
<div class="title">
<!-- TODO need subject-->
<a class="subject" href={changelist.canonicalURL}>{changelist.commit.subject}</a>
{#if !alwaysExpanded && changelist.commit.body && !$isViewportMobile}
<Button
variant="secondary"
size="sm"
on:click={() => (expanded = !expanded)}
aria-label="{expanded ? 'Hide' : 'Show'} changelist message"
>
<Icon icon={ILucideEllipsis} inline aria-hidden />
</Button>
{/if}
</div>
<div class="author">
submitted by <strong>{author.person.name}</strong>
<Timestamp date={commitDate} />
</div>
{#if changelist.commit.body}
<div class="message" class:expanded>
{#if $isViewportMobile}
{#if expanded}
<Button variant="secondary" size="lg" display="block" on:click={() => (expanded = false)}>
Close
</Button>
{:else}
<Button variant="secondary" size="sm" display="block" on:click={() => (expanded = true)}>
Show changelist message
</Button>
{/if}
{/if}
<pre>{changelist.commit.body}</pre>
</div>
{/if}
</div>
<style lang="scss">
.root {
display: grid;
overflow: hidden;
grid-template-columns: auto 1fr;
grid-template-areas: 'avatar title' 'avatar author' '. message';
column-gap: 1rem;
@media (--mobile) {
grid-template-columns: auto 1fr;
grid-template-areas: 'avatar title' 'author author' 'message message';
row-gap: 0.5rem;
}
}
.avatar {
grid-area: avatar;
display: flex;
gap: 0.25rem;
align-self: center;
}
.title {
grid-area: title;
align-self: center;
display: flex;
gap: 0.5rem;
align-items: center;
overflow: hidden;
.subject {
font-weight: 600;
flex: 0 1 auto;
color: var(--body-color);
min-width: 0;
@media (--sm-breakpoint-up) {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
}
.author {
grid-area: author;
color: var(--text-muted);
}
.message {
grid-area: message;
overflow: hidden;
@media (--mobile) {
&.expanded {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
display: flex;
flex-direction: column;
background-color: var(--color-bg-1);
}
}
}
pre {
display: none;
margin-top: 0.5rem;
margin-bottom: 1.5rem;
font-size: 0.75rem;
max-width: 100%;
word-wrap: break-word;
white-space: pre-wrap;
.expanded & {
display: block;
}
@media (--mobile) {
padding: 0.5rem;
overflow: auto;
margin: 0;
}
}
</style>

View File

@ -71,7 +71,7 @@
padding: '0 1.5ex',
},
'.cm-line': {
lineHeight: '1.54',
lineHeight: 'var(--code-line-height)',
padding: '0',
},
'.selected-line': {
@ -131,6 +131,7 @@
import { browser } from '$app/environment'
import { goto } from '$app/navigation'
import { getExplorePanelContext } from '$lib/codenav/ExplorePanel.svelte'
import type { LineOrPositionOrRange } from '$lib/common'
import { type CodeIntelAPI, Occurrence } from '$lib/shared'
import {
@ -166,7 +167,7 @@
getScrollSnapshot as getScrollSnapshot_internal,
} from './codemirror/utils'
import { registerHotkey } from './Hotkey'
import { goToDefinition, openImplementations, openReferences } from './repo/blob'
import { goToDefinition } from './repo/blob'
import { createLocalWritable } from './stores'
export let blobInfo: BlobInfo
@ -229,15 +230,23 @@
filePath: blobInfo.filePath,
languages: blobInfo.languages,
}
const { openReferences, openDefinitions, openImplementations } = getExplorePanelContext()
$: codeIntelExtension = codeIntelAPI
? createCodeIntelExtension({
api: {
api: codeIntelAPI,
documentInfo: documentInfo,
goToDefinition: (view, definition, options) =>
goToDefinition(documentInfo, view, definition, options),
openReferences,
openImplementations,
goToDefinition: (view, definition, options) => {
if (definition.type === 'multiple') {
// Open the explore panel with the definitions
openDefinitions({ documentInfo, occurrence: definition.occurrence })
} else {
goToDefinition(documentInfo, view, definition, options)
}
},
openReferences: (_view, documentInfo, occurrence) => openReferences({ documentInfo, occurrence }),
openImplementations: (_view, documentInfo, occurrence) =>
openImplementations({ documentInfo, occurrence }),
createTooltipView: options => new HovercardView(options.view, options.token, options.hovercardData),
},
// TODO(fkling): Support tooltip pinning

View File

@ -7,6 +7,8 @@
import Tooltip from '$lib/Tooltip.svelte'
import type { Commit } from './Commit.gql'
import { isViewportMobile } from './stores'
import Button from './wildcard/Button.svelte'
export let commit: Commit
export let alwaysExpanded: boolean = false
@ -22,12 +24,13 @@
return committer
}
$: expanded = alwaysExpanded
$: author = commit.author
$: committer = getCommitter(commit) ?? author
$: committerIsAuthor = committer.person.email === author.person.email
$: commitDate = new Date(committer.date)
$: authorAvatarTooltip = author.person.name + (committer ? ' (author)' : '')
let expanded = alwaysExpanded
</script>
<div class="root">
@ -35,54 +38,79 @@
<Tooltip tooltip={authorAvatarTooltip}>
<Avatar avatar={author.person} />
</Tooltip>
</div>
{#if !committerIsAuthor}
<div class="avatar">
{#if !committerIsAuthor}
<Tooltip tooltip="{committer.person.name} (committer)">
<Avatar avatar={committer.person} />
</Tooltip>
</div>
{/if}
<div class="info">
<span class="title">
<a class="subject" href={commit.canonicalURL}>{commit.subject}</a>
{#if !alwaysExpanded && commit.body}
<button
type="button"
on:click={() => (expanded = !expanded)}
aria-label="{expanded ? 'Hide' : 'Show'} commit message"
>
<Icon icon={ILucideEllipsis} inline aria-hidden />
</button>
{/if}
</span>
<span>
{#if !committerIsAuthor}authored by <strong>{author.person.name}</strong> and{/if}
committed by <strong>{committer.person.name}</strong>
<Timestamp date={commitDate} />
</span>
{#if expanded && commit.body}
<pre>{commit.body}</pre>
{/if}
</div>
<div class="title">
<a class="subject" href={commit.canonicalURL}>{commit.subject}</a>
{#if !alwaysExpanded && commit.body && !$isViewportMobile}
<Button
variant="secondary"
size="sm"
on:click={() => (expanded = !expanded)}
aria-label="{expanded ? 'Hide' : 'Show'} commit message"
>
<Icon icon={ILucideEllipsis} inline aria-hidden />
</Button>
{/if}
</div>
<div class="author">
{#if !committerIsAuthor}authored by <strong>{author.person.name}</strong> and{/if}
committed by <strong>{committer.person.name}</strong>
<Timestamp date={commitDate} />
</div>
{#if commit.body}
<div class="message" class:expanded>
{#if $isViewportMobile}
{#if expanded}
<Button variant="secondary" size="lg" display="block" on:click={() => (expanded = false)}>
Close
</Button>
{:else}
<Button variant="secondary" size="sm" display="block" on:click={() => (expanded = true)}>
Show commit message
</Button>
{/if}
{/if}
<pre>{commit.body}</pre>
</div>
{/if}
</div>
<style lang="scss">
.root {
display: flex;
gap: 1rem;
display: grid;
overflow: hidden;
grid-template-columns: auto 1fr;
grid-template-areas: 'avatar title' 'avatar author' '. message';
column-gap: 1rem;
@media (--mobile) {
grid-template-columns: auto 1fr;
grid-template-areas: 'avatar title' 'author author' 'message message';
row-gap: 0.5rem;
}
}
.info {
.avatar {
grid-area: avatar;
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
gap: 0.25rem;
align-self: center;
}
.title {
grid-area: title;
align-self: center;
display: flex;
gap: 0.5rem;
align-items: center;
overflow: hidden;
.subject {
font-weight: 600;
@ -98,35 +126,50 @@
}
}
.avatar {
flex: 0 0 auto;
display: flex;
width: 2.75rem;
height: 2.75rem;
font-size: 1.5rem;
}
span {
.author {
grid-area: author;
color: var(--text-muted);
}
button {
color: var(--body-color);
border: 1px solid var(--secondary);
cursor: pointer;
.message {
grid-area: message;
overflow: hidden;
@media (--xs-breakpoint-down) {
align-self: flex-start;
@media (--mobile) {
&.expanded {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: 0;
display: flex;
flex-direction: column;
background-color: var(--color-bg-1);
}
}
}
pre {
display: none;
margin-top: 0.5rem;
margin-bottom: 1.5rem;
font-size: 0.75rem;
overflow: visible;
max-width: 100%;
word-wrap: break-word;
white-space: pre-wrap;
.expanded & {
display: block;
}
@media (--mobile) {
padding: 0.5rem;
overflow: auto;
margin: 0;
}
}
</style>

View File

@ -4,30 +4,36 @@ A component to display the keyboard shortcuts for the application.
<script lang="ts">
import { isMacPlatform } from '$lib/common'
import { formatShortcutParts, type Keys } from '$lib/Hotkey'
import { isViewportMobile } from './stores'
export let shortcut: Keys
export let inline: boolean = false
const separator = isMacPlatform() ? '' : '+'
$: parts = (() => {
const result: string[] = []
let parts = formatShortcutParts(shortcut)
for (let i = 0; i < parts.length; i++) {
if (i > 0) {
result.push(separator)
}
result.push(parts[i])
}
return result
})()
// No need to do this work if we are on a mobile device
$: parts = $isViewportMobile
? []
: (() => {
const result: string[] = []
let parts = formatShortcutParts(shortcut)
for (let i = 0; i < parts.length; i++) {
if (i > 0) {
result.push(separator)
}
result.push(parts[i])
}
return result
})()
</script>
<kbd class:inline>
{#each parts as part}
<span>{part}</span>
{/each}
</kbd>
{#if !$isViewportMobile}
<kbd class:inline>
{#each parts as part}
<span>{part}</span>
{/each}
</kbd>
{/if}
<style lang="scss">
kbd {

View File

@ -0,0 +1,55 @@
<script lang="ts" context="module">
import { Story } from '@storybook/addon-svelte-csf'
import LoadingSpinner from './LoadingSpinner.svelte'
export const meta = {
component: LoadingSpinner,
}
</script>
<Story name="Default">
<h3>Default</h3>
<div class="wrapper">
<LoadingSpinner />
</div>
<h3>--size="2rem"</h3>
<div class="wrapper">
<LoadingSpinner --size="2rem" />
</div>
<h3>center={false}</h3>
<div class="wrapper">
<LoadingSpinner center={false} />
</div>
<h3>inline={true}</h3>
<div class="wrapper">
<LoadingSpinner inline />
</div>
<button>
<LoadingSpinner inline />
<span>Loading...</span>
</button>
<br />
<button style="font-size: 48px">
<LoadingSpinner inline />
<span>Loading...</span>
</button>
</Story>
<style lang="scss">
.wrapper {
display: flex;
margin: 1rem;
width: 10rem;
height: 10rem;
background-color: lightblue;
}
button span {
vertical-align: middle;
}
</style>

View File

@ -3,8 +3,8 @@
export let center = true
</script>
<div class:center>
<div class="loading-spinner" class:inline aria-label="loading" aria-live="polite" />
<div class:center class:inline>
<div class="loading-spinner" aria-label="loading" aria-live="polite" />
</div>
<style lang="scss">
@ -14,6 +14,11 @@
align-items: center;
flex: 1;
justify-content: center;
}
.inline {
display: contents;
}
.loading-spinner {
@ -28,13 +33,12 @@
width: var(--size, 1rem);
height: var(--size, 1rem);
&.inline {
.inline & {
width: #{(16 / 14)}em;
height: #{(16 / 14)}em;
vertical-align: bottom;
display: inline-flex;
align-items: center;
vertical-align: middle;
display: inline-block;
}
border-radius: 50%;

View File

@ -5,6 +5,7 @@
import { createHotkey } from '$lib/Hotkey'
import { popover, onClickOutside, portal } from './dom'
import { isViewportMobile } from './stores'
/**
* Show the popover when hovering over the trigger.
@ -15,6 +16,7 @@
export let hoverDelay: number = 500
export let hoverCloseDelay: number = 150
export let closeOnEsc: boolean = true
export let flip: boolean = true
export let trigger: HTMLElement | null = null
export let target: HTMLElement | undefined = undefined
@ -94,7 +96,6 @@
trigger.addEventListener('mouseenter', handleMouseEnterTrigger)
trigger.addEventListener('mouseleave', handleMouseLeaveTrigger)
trigger.addEventListener('mousemove', handleMouseMoveTrigger)
trigger.addEventListener('click', close)
window.addEventListener('blur', close)
}
@ -102,7 +103,6 @@
trigger.removeEventListener('mouseenter', handleMouseEnterTrigger)
trigger.removeEventListener('mouseleave', handleMouseLeaveTrigger)
trigger.removeEventListener('mousemove', handleMouseMoveTrigger)
trigger.removeEventListener('click', close)
window.removeEventListener('blur', close)
}
@ -111,7 +111,9 @@
let oldTrigger: HTMLElement | null
$: {
oldTrigger && showOnHover && unwatchTrigger(oldTrigger)
trigger && showOnHover && watchTrigger(trigger)
if (!$isViewportMobile) {
trigger && showOnHover && watchTrigger(trigger)
}
oldTrigger = trigger
}
@ -155,6 +157,9 @@
placement,
offset,
shift: { padding: 4 },
flip: flip ? {
fallbackAxisSideDirection: 'start',
} : undefined,
},
}}
on:click-outside={handleClickOutside}
@ -178,7 +183,7 @@
border: 1px solid var(--dropdown-border-color);
border-radius: var(--popover-border-radius);
// Ensure child elements do not overflow the border radius
overflow: hidden;
overflow-y: scroll;
// We always display the popover on hover, but there may not be anything
// inside until something we load something. This ensures we do not

View File

@ -8,9 +8,11 @@
import { afterUpdate, createEventDispatcher } from 'svelte'
export let margin: number
export let viewport: HTMLElement | undefined = undefined
export let scroller: HTMLElement | undefined = undefined
export function capture(): Capture {
return { scroll: scroller.scrollTop }
return { scroll: scroller?.scrollTop || 0 }
}
export function restore(data?: Capture) {
@ -31,14 +33,13 @@
const dispatch = createEventDispatcher<{ more: void }>()
let viewport: HTMLElement
let scroller: HTMLElement
function handleScroll() {
const remaining = scroller.scrollHeight - (scroller.scrollTop + viewport.clientHeight)
if (scroller && viewport) {
const remaining = scroller.scrollHeight - (scroller.scrollTop + (viewport?.clientHeight ?? 0))
if (remaining < margin) {
dispatch('more')
if (remaining < margin) {
dispatch('more')
}
}
}
@ -46,13 +47,13 @@
// This premptively triggers a 'more' event when the scrollable content is smaller than than
// scroller. Without this, the 'more' event would not be triggered because there is nothing
// to scroll.
if (scroller.scrollHeight <= scroller.clientHeight) {
if (scroller && scroller.scrollHeight <= scroller.clientHeight) {
dispatch('more')
}
})
</script>
<div class="viewport" bind:this={viewport}>
<div class="viewport" bind:this={viewport} data-viewport>
<div class="scroller" bind:this={scroller} on:scroll={handleScroll} data-scroller>
<slot />
</div>

View File

@ -1,45 +0,0 @@
<script lang="ts" context="module">
import Separator, { getSeparatorPosition } from '$lib/Separator.svelte'
import { Story } from '@storybook/addon-svelte-csf'
export const meta = {
component: Separator,
}
</script>
<script lang="ts">
const currentPosition = getSeparatorPosition('separator-example', 0.5)
$: width = `${$currentPosition * 100}%`
</script>
<Story name="Default">
<section>
<div class="left match-highlight" style:min-width={width} style:max-width={width}>Left content</div>
<Separator {currentPosition} />
<div class="right">Right content</div>
</section>
</Story>
<style lang="scss">
section {
display: flex;
height: 90vh;
}
div {
padding: 1rem;
display: flex;
align-items: center;
justify-content: center;
background-clip: content-box;
}
.left {
background-color: var(--color-bg-2);
}
.right {
flex: 1;
background-color: var(--color-bg-2);
}
</style>

View File

@ -1,106 +0,0 @@
<script lang="ts" context="module">
import { derived, type Writable } from 'svelte/store'
import { createLocalWritable } from '$lib/stores'
const dividerStore = createLocalWritable<Record<string, number>>('dividers', {})
export function getSeparatorPosition(name: string, defaultValue: number): Writable<number> {
const { subscribe } = derived(dividerStore, dividers => dividers[name] ?? defaultValue)
return {
subscribe,
set(value) {
dividerStore.update(dividers => ({ ...dividers, [name]: value }))
},
update(updater) {
dividerStore.update(dividers => ({ ...dividers, [name]: updater(dividers[name]) }))
},
}
}
</script>
<script lang="ts">
/**
* Store to write current position (0-1) to.
*/
export let currentPosition: Writable<number>
let divider: HTMLElement | null = null
let offset = 0
let dragging = false
function onMouseMove(event: MouseEvent) {
event.preventDefault()
if (divider?.parentElement) {
let width = (event.x - offset) / divider.parentElement.clientWidth
if (width < 0) {
width = 0
} else if (width > 1) {
width = 1
}
$currentPosition = width
}
}
function endResize() {
dragging = false
window.removeEventListener('mousemove', onMouseMove)
window.removeEventListener('mouseup', endResize)
}
function startResize(event: MouseEvent) {
event.preventDefault()
if (divider?.parentElement) {
dragging = true
offset = divider.parentElement.getBoundingClientRect().x + divider.clientWidth
window.addEventListener('mousemove', onMouseMove)
window.addEventListener('mouseup', endResize)
}
}
</script>
<!-- TODO: implement keyboard handlers. See https://www.w3.org/WAI/ARIA/apg/patterns/windowsplitter/ -->
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<div
bind:this={divider}
role="separator"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={$currentPosition}
class:dragging
on:mousedown={startResize}
>
<!-- spacer is used to increase the interactable surface-->
<div class="spacer" />
</div>
<style lang="scss">
div[role='separator'] {
flex-shrink: 0;
position: relative;
width: 1px;
background-color: var(--border-color);
cursor: col-resize;
.spacer {
position: absolute;
top: 0;
bottom: 0;
left: -5px;
margin-left: -50%;
width: 10px;
}
&.dragging {
z-index: 1;
outline: 1px solid var(--oc-blue-3);
background-color: var(--oc-blue-3);
}
&:hover:not(.dragging) {
z-index: 1;
outline: 1px solid var(--border-color);
}
}
</style>

View File

@ -26,6 +26,10 @@
*/
export let selected: number | null = 0
export let toggable = false
/**
* Whether or not to show the tab header when there is only one tab.
*/
export let showSingleTabHeader = false
const dispatch = createEventDispatcher<{ select: number | null }>()
const id = uuid.v4()
@ -66,12 +70,14 @@
</script>
<div class="tabs" data-tabs>
<header>
<TabsHeader {id} tabs={$tabs} selected={$selectedTab} on:select={selectTab} />
<div class="actions">
<slot name="header-actions" />
</div>
</header>
{#if $tabs.length > 1 || showSingleTabHeader}
<header>
<TabsHeader {id} tabs={$tabs} selected={$selectedTab} on:select={selectTab} />
<div class="actions">
<slot name="header-actions" />
</div>
</header>
{/if}
<slot />
</div>
@ -87,10 +93,12 @@
display: flex;
align-items: center;
border-bottom: 1px solid var(--border-color);
gap: 2rem;
.actions {
margin-left: auto;
margin-right: var(--tabs-horizontal-spacing);
min-width: 0;
}
}
}

View File

@ -66,8 +66,7 @@
display: flex;
align-items: stretch;
justify-content: var(--align-tabs, center);
gap: var(--tabs-gap, 0);
justify-content: var(--tabs-header-align, flex-start);
}
[role='tab'] {
@ -77,7 +76,7 @@
align-items: center;
min-height: 2rem;
padding: 0.25rem 0.75rem;
color: var(--text-muted);
color: var(--text-body);
display: inline-flex;
flex-flow: row nowrap;
justify-content: center;
@ -114,13 +113,15 @@
span {
display: inline-block;
// Hidden rendering of the bold tab title to prevent
// shifting when the tab is selected.
&::before {
content: attr(data-tab-title);
display: block;
height: 0;
visibility: hidden;
&[data-tab-title] {
// Hidden rendering of the bold tab title to prevent
// shifting when the tab is selected.
&::before {
content: attr(data-tab-title);
display: block;
height: 0;
visibility: hidden;
}
}
}

View File

@ -5,7 +5,9 @@
</script>
<script lang="ts">
import { popover, portal, uniqueID } from './dom'
import { onMount, tick } from 'svelte'
import { type PopoverOptions, popover, portal, uniqueID } from './dom'
/**
* The content of the tooltip.
@ -41,8 +43,24 @@
shift: {
padding: 4,
},
onSize(element, { availableWidth, availableHeight }) {
Object.assign(element.style, {
maxWidth: `min(var(--tooltip-max-width), ${availableWidth}px)`,
maxHeight: `${availableHeight}px`,
})
},
} satisfies PopoverOptions
$: if (target && tooltip) {
target.setAttribute('aria-label', tooltip)
}
$: {
onMount(async () => {
// We need to wait for the element to be rendered before we can check whether it
// is part of the layout.
// (this fixes and issue where the tooltip would not show up in hovercards)
await tick()
let node = wrapper?.firstElementChild
// Use `getClientRects` to check if the element is part of the layout.
// For example, an element with `display: contents` will not be part of the layout.
@ -54,10 +72,7 @@
if (node) {
target = node
}
}
$: if (target && tooltip) {
target.setAttribute('aria-label', tooltip)
}
})
</script>
<!-- TODO: close tooltip on escape -->
@ -73,12 +88,16 @@
on:mouseleave={hide}
on:focusin={show}
on:focusout={hide}
data-tooltip-root
>
<slot />
</div>
{#if (alwaysVisible || visible) && target && tooltip}
<div role="tooltip" {id} use:popover={{ reference: target, options }} use:portal>
data-tooltip-root><!--
--><slot /><!--
--></div
><!--
-->{#if (alwaysVisible || visible) && target && tooltip}<div
role="tooltip"
{id}
use:popover={{ reference: target, options }}
use:portal
>
<div class="content">{tooltip}</div>
<div data-arrow />
</div>

View File

@ -31,6 +31,7 @@
$: selected = $treeState.selected === nodeID
$: tabindex = $treeState.focused === nodeID ? 0 : -1
$: children = expandable && expanded ? treeProvider.fetchChildren(entry) : null
$: disableScope = $treeState.disableScope
let level = getContext<TreeNodeContext>('tree-node-nesting')?.level ?? 0
setContext('tree-node-nesting', { level: level + 1 })
@ -76,30 +77,37 @@
{tabindex}
data-treeitem
data-node-id={nodeID}
class:disable-scope={disableScope}
style="--tree-node-nested-level: {level}"
>
<span bind:this={label} class="label" data-treeitem-label class:expandable>
<div bind:this={label} class="label" data-treeitem-label class:expandable>
<!-- TODO: scoping is an operation specific to the file tree, but this
is intended to be a generic tree component. We should not add a scope
button here. -->
<Button variant="icon" on:click={handleScopeChange} data-scope-button>
<Icon icon={ILucideFocus} inline aria-hidden="true" />
</Button>
<!-- hide the open/close button to preserve alignment with expandable entries -->
{#if expandable}
<!-- We have to stop even propagation because the tree root listens for click events for
selecting items. We don't want the item to be selected when the open/close button is pressed.
-->
<Button
variant="icon"
on:click={event => {
event.stopPropagation()
toggleOpen()
}}
tabindex={-1}
>
<Icon icon={expanded ? ILucideChevronDown : ILucideChevronRight} inline />
</Button>
{/if}
<slot {entry} {expanded} toggle={toggleOpen} {label} />
</span>
<div class="indented">
{#if expandable}
<!-- We have to stop even propagation because the tree root
listens for click events for selecting items. We don't want the
item to be selected when the open/close button is pressed. -->
<Button
variant="icon"
on:click={event => {
event.stopPropagation()
toggleOpen()
}}
tabindex={-1}
aria-label="{expanded ? 'Collapse' : 'Expand'} subtree"
>
<Icon icon={expanded ? ILucideChevronDown : ILucideChevronRight} inline aria-hidden="true" />
</Button>
{/if}
<slot {entry} {expanded} toggle={toggleOpen} {label} />
</div>
</div>
{#if expanded && children}
{#await children}
<div class="loading">
@ -122,68 +130,74 @@
<style lang="scss">
$shiftWidth: 1.25rem;
$gap: 0.25rem;
$indentSize: calc(var(--tree-node-nested-level) * #{$shiftWidth});
[role='treeitem'] {
border-radius: var(--border-radius);
li[role='treeitem'] {
--scope-size: calc(var(--icon-inline-size) + #{$gap} - 1px);
&.disable-scope {
--scope-size: 0px;
:global([data-scope-button]) {
display: none;
}
}
&[tabindex='0']:focus {
box-shadow: none;
> .label {
box-shadow: var(--focus-box-shadow);
box-shadow: var(--focus-shadow-inset);
}
}
}
.loading {
// Indent with two rem since loading represents next nested level
margin-left: calc(var(--tree-node-nested-level) * #{$shiftWidth} + 2 * var(--icon-inline-size) + 2 * #{$gap});
margin-top: 0.25rem;
}
.label {
display: flex;
gap: $gap;
padding: 0.2rem $gap;
align-items: center;
.label {
display: flex;
gap: $gap;
padding: 0.2rem $gap;
justify-content: space-between;
align-items: center;
// Change icon color based on selected item state
--icon-color: var(--tree-node-expand-icon-color);
color: var(--tree-node-label-color, var(--text-body));
// Change icon color based on selected item state
--icon-color: var(--tree-node-expand-icon-color);
color: var(--tree-node-label-color, var(--text-body));
li[data-treeitem][aria-selected='true'] > & {
--icon-color: currentColor;
--file-icon-color: currentColor;
color: var(--tree-node-label-color, var(--body-bg));
}
:global([data-scope-button]) {
visibility: hidden;
margin-right: calc(var(--tree-node-nested-level) * #{$shiftWidth});
}
&.expandable:hover,
&.expandable:focus {
:global([data-scope-button]) {
visibility: visible;
visibility: hidden;
}
&.expandable:hover,
&.expandable:focus {
:global([data-scope-button]) {
visibility: visible;
}
}
.indented {
display: inherit;
gap: inherit;
margin-left: $indentSize;
width: 100%;
}
}
}
ul {
position: relative;
isolation: isolate;
&::before {
position: absolute;
content: '';
border-left: 1px solid var(--secondary);
height: 100%;
transform: translateX(
calc(var(--tree-node-nested-level) * #{$shiftWidth} + var(--icon-inline-size) * 1.5 + #{$gap} + 2px)
);
z-index: 1;
.loading {
// Indent with two rem since loading represents next nested level
margin-left: calc(var(--scope-size) + #{$indentSize} + 2 * #{$gap});
margin-top: 0.25rem;
}
ul {
position: relative;
isolation: isolate;
// The visual guide line for expanded subtrees
&::before {
position: absolute;
content: '';
border-left: 1px solid var(--secondary);
height: 100%;
transform: translateX(
calc(#{$gap} + var(--scope-size) + #{$indentSize} + var(--icon-inline-size) / 2 - 1px)
);
z-index: 1;
}
}
}
</style>

View File

@ -7,7 +7,7 @@ export interface TreeProvider<T> {
*/
getEntries(): T[]
/**
* Whether or not the provided entry is has (possibly) children or not.
* Whether or not the provided entry has (possibly) children or not.
*/
isExpandable(entry: T): boolean
/**
@ -29,6 +29,7 @@ export interface SingleSelectTreeState {
focused: string
selected: string
expandedNodes: Set<string>
disableScope: boolean
}
export type TreeState = SingleSelectTreeState
@ -38,6 +39,7 @@ export function createEmptySingleSelectTreeState(): SingleSelectTreeState {
focused: '',
selected: '',
expandedNodes: new Set(),
disableScope: false,
}
}

Some files were not shown because too many files have changed in this diff Show More