Chat composer: '#' context dropdown for issues (#1861) (archie)
ci/woodpecker/pr/quality Pipeline was successful
Quality / check (pull_request) Successful in 4m18s

This commit is contained in:
archie committed 2026-11-12 14:54:01 +11:00
1 parent a9aacab79d
commit 09c2c55762
16 files changed
+972 -91

No files matched your search

+37
View File
@@ -24,5 +24,42 @@ module.exports = async ({ page, go, shot }) => {
await composer.press('Enter');
assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits');
assert.equal(await composer.inputValue(), '');
await page.route('**/api/issues', async route => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify([
{
owner: 'sam',
repository: 'archie',
number: 1861,
title: "Chat composer: '#' context dropdown for issues",
},
{
owner: 'sam',
repository: 'archie',
number: 1842,
title: 'Retry stalled task runs',
},
]),
});
});
await composer.fill('Implement #');
const issuesPalette = page.getByRole('listbox', { name: 'Issues' });
await issuesPalette.waitFor();
assert.equal(await issuesPalette.getByRole('option').count(), 2);
await composer.press('Escape');
await issuesPalette.waitFor({ state: 'hidden' });
await composer.fill('Implement #184');
await issuesPalette.waitFor();
assert.equal(await issuesPalette.getByRole('option').count(), 1);
await composer.press('Tab');
await issuesPalette.waitFor({ state: 'hidden' });
assert.equal(await composer.inputValue(), 'Implement #1842 ');
await composer.fill('');
await shot('chat-composition');
};
+4 -1
View File
@@ -22,6 +22,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/harnesssession"
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
"github.com/samcharles93/archie-core/internal/infrastructure/rpcidentity"
@@ -211,7 +212,9 @@ func (b *boot) setupDaemonRPC(ctx context.Context) {
workspaces, _ := b.stateStore.(access.WorkspaceLister)
callers := rpcidentity.Callers{Principals: b.d.Principals, Workspaces: workspaces}
srv := grpc.NewServer(append(servicekit.ServerLimits(), creds, grpc.ChainUnaryInterceptor(callers.Unary()), grpc.ChainStreamInterceptor(callers.Stream()))...)
daemonpb.RegisterDaemonServiceServer(srv, &repositoryServer{boot: b})
repoSrv := &repositoryServer{boot: b}
daemonpb.RegisterDaemonServiceServer(srv, repoSrv)
daemonrpc.RegisterIssueService(srv, repoSrv)
// Terminal sessions still require certificates and a container launcher.
if id != nil && b.kitLauncher != nil && b.containerPool != nil {
manager := &harnesssession.Manager{Launcher: b.kitLauncher, Client: b.containerPool.Client(), Profile: func(name string) (config.AgentProfile, error) { return b.cfgHolder.Get().Containers.Profile(name) }, TTL: setupSessionTTL}
@@ -32,6 +32,7 @@ import (
"github.com/samcharles93/archie-core/internal/forge"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/worktree"
)
@@ -305,6 +306,7 @@ func TestConnectionAccountRefusesRedirects(t *testing.T) {
type recordingForge struct {
forge.Forge
merged bool
issues map[string][]forge.Issue
}
func (f *recordingForge) MergePR(context.Context, string, string, int) error {
@@ -312,6 +314,14 @@ func (f *recordingForge) MergePR(context.Context, string, string, int) error {
return nil
}
func (f *recordingForge) IssuesWithLabel(_ context.Context, owner, repo, _ string) ([]forge.Issue, error) {
open, ok := f.issues[owner+"/"+repo]
if !ok {
return nil, errors.New("forge unavailable")
}
return open, nil
}
// An operator merge goes through the repository's own connection: the
// instance's default forge may be another host that does not have the repo.
func TestMergeUsesRepositoryConnection(t *testing.T) {
@@ -338,3 +348,59 @@ func TestMergeUsesRepositoryConnection(t *testing.T) {
})
}
}
func TestListIssues(t *testing.T) {
docs := &repositoryDocuments{
repos: map[org.OrgID][]config.Repo{
"org-a": {
{Owner: "acme", Name: "app", Connection: "gitea"},
{Owner: "acme", Name: "unbound"},
},
},
}
fg := &recordingForge{
issues: map[string][]forge.Issue{
"acme/app": {
{Number: 1861, Title: "Chat composer: '#' context dropdown for issues", Labels: []string{"enhancement"}},
{Number: 1842, Title: "Retry stalled task runs"},
},
},
}
b := &boot{
controlPlane: controlplanestore.NewRPCClient(docs),
d: &daemon.Daemon{Access: infraaccess.New(access.ShippedOrgPolicies("org-a"))},
log: slog.New(slog.DiscardHandler),
}
srv := &repositoryServer{
boot: b,
forge: func(_ context.Context, _, _ string) (forge.IssueForge, error) {
return fg, nil
},
}
req := &daemonrpc.ListIssuesRequest{}
if _, err := srv.ListIssues(t.Context(), req); status.Code(err) != codes.Unauthenticated {
t.Fatalf("unauthenticated ListIssues: %v", err)
}
deniedCtx := access.WithPrincipal(t.Context(), access.Principal{IdentityID: "outsider", Org: "org-a"})
if _, err := srv.ListIssues(deniedCtx, req); status.Code(err) != codes.PermissionDenied {
t.Fatalf("unauthorized ListIssues: %v", err)
}
member := access.Principal{
IdentityID: "member",
Kind: identity.KindUser,
Org: "org-a",
Memberships: []org.Membership{{IdentityID: "member", OrgID: "org-a", Role: org.RoleViewer}},
}
memberCtx := access.WithPrincipal(t.Context(), member)
res, err := srv.ListIssues(memberCtx, req)
if err != nil {
t.Fatalf("ListIssues error: %v", err)
}
if len(res.Issues) != 2 || res.Issues[0].Number != 1861 || res.Issues[0].Owner != "acme" || res.Issues[0].Repository != "app" {
t.Fatalf("unexpected issues: %+v", res.Issues)
}
delete(fg.issues, "acme/app")
if _, err := srv.ListIssues(memberCtx, req); status.Code(err) != codes.Unavailable {
t.Fatalf("failed forge read: %v", err)
}
}
+77 -1
View File
@@ -18,14 +18,90 @@ import (
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
"github.com/samcharles93/archie-core/internal/daemon"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/forge"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
"github.com/samcharles93/archie-core/internal/worktree"
)
const maxListedIssues = 200
type repositoryServer struct {
pb.UnimplementedDaemonServiceServer
boot *boot
boot *boot
forge func(ctx context.Context, owner, repo string) (forge.IssueForge, error)
}
func (s *repositoryServer) ListIssues(ctx context.Context, _ *daemonrpc.ListIssuesRequest) (*daemonrpc.ListIssuesResponse, error) {
b := s.boot
caller, ok := access.PrincipalFromContext(ctx)
if !ok || caller.IdentityID == "" {
return nil, status.Error(codes.Unauthenticated, "Sign in before listing issues.")
}
if b.d == nil || b.d.Access == nil || b.controlPlane == nil {
return nil, status.Error(codes.Unavailable, "Issues are temporarily unavailable.")
}
decision := b.d.Access.Authorize(caller, access.ActionRead, access.Resource{Kind: access.KindTask, Org: caller.Org}, access.Context{})
if !decision.Allowed {
return nil, status.Error(codes.PermissionDenied, "You do not have permission to list issues.")
}
ctx, cancel := context.WithTimeout(org.WithOrg(ctx, caller.Org), 30*time.Second)
defer cancel()
var repos []config.Repo
_, found, err := b.controlPlane.Query(ctx, controlplanestore.RepositoryPoliciesKind, func(value []byte) error { return json.Unmarshal(value, &repos) })
if err != nil {
return nil, status.Error(codes.Unavailable, "Configured repositories are unavailable.")
}
if !found || len(repos) == 0 {
return &daemonrpc.ListIssuesResponse{}, nil
}
resolveForge := s.forge
if resolveForge == nil {
resolveForge = b.issueForge
}
return collectRepositoryIssues(ctx, repos, resolveForge)
}
func collectRepositoryIssues(ctx context.Context, repos []config.Repo, resolveForge func(context.Context, string, string) (forge.IssueForge, error)) (*daemonrpc.ListIssuesResponse, error) {
var (
issues []daemonrpc.Issue
attempted int
failed int
)
for _, repo := range repos {
if repo.Owner == "" || repo.Name == "" || repo.Connection == "" {
continue
}
attempted++
fg, err := resolveForge(ctx, repo.Owner, repo.Name)
if err != nil {
failed++
continue
}
open, err := fg.IssuesWithLabel(ctx, repo.Owner, repo.Name, "")
if err != nil {
failed++
continue
}
for _, issue := range open {
issues = append(issues, daemonrpc.Issue{
Owner: repo.Owner,
Repository: repo.Name,
Number: int32(issue.Number),
Title: issue.Title,
Labels: issue.Labels,
})
if len(issues) >= maxListedIssues {
return &daemonrpc.ListIssuesResponse{Issues: issues}, nil
}
}
}
if attempted > 0 && failed == attempted {
return nil, status.Error(codes.Unavailable, "Repository issues are temporarily unavailable.")
}
return &daemonrpc.ListIssuesResponse{Issues: issues}, nil
}
func (s *repositoryServer) CheckRepository(ctx context.Context, r *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error) {
+1
View File
@@ -149,6 +149,7 @@ func wireDaemon(opts Options, srv *webui.Server, cleanups *[]func()) error {
return fmt.Errorf("repository checks: %w", err)
}
srv.RepositoryChecks = checks
srv.Issues = checks
*cleanups = append(*cleanups, closeChecks)
return wireHarness(opts, srv, cleanups)
}
+97 -2
View File
@@ -3,8 +3,10 @@ package daemonrpc
import (
"context"
"encoding/json"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/wrapperspb"
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
"github.com/samcharles93/archie-core/internal/domain/presence"
@@ -13,7 +15,86 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
)
type Client struct{ rpc pb.DaemonServiceClient }
const listIssuesMethod = "/daemon.v1.IssueService/ListIssues"
// Issue is an open issue returned by the daemon's issue listing RPC.
type Issue struct {
Owner string `json:"owner"`
Repository string `json:"repository"`
Number int32 `json:"number"`
Title string `json:"title"`
Labels []string `json:"labels,omitempty"`
}
// ListIssuesRequest asks the daemon for open issues across the caller's org.
type ListIssuesRequest struct{}
// ListIssuesResponse holds the open issues the daemon resolved.
type ListIssuesResponse struct {
Issues []Issue `json:"issues"`
}
// IssueServiceServer is implemented by the daemon's repository server.
type IssueServiceServer interface {
ListIssues(context.Context, *ListIssuesRequest) (*ListIssuesResponse, error)
}
// RegisterIssueService registers the open-issues RPC on the daemon's gRPC server.
func RegisterIssueService(s grpc.ServiceRegistrar, srv IssueServiceServer) {
s.RegisterService(&issueServiceDesc, srv)
}
var issueServiceDesc = grpc.ServiceDesc{
ServiceName: "daemon.v1.IssueService",
HandlerType: (*IssueServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListIssues",
Handler: handleListIssues,
},
},
}
func handleListIssues(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {
in := new(wrapperspb.BytesValue)
if err := dec(in); err != nil {
return nil, err
}
call := func(ctx context.Context) (any, error) {
impl, ok := srv.(IssueServiceServer)
if !ok {
return wrapperspb.Bytes(nil), nil
}
resp, err := impl.ListIssues(ctx, &ListIssuesRequest{})
if err != nil {
return nil, err
}
var issues []Issue
if resp != nil {
issues = resp.Issues
}
data, err := json.Marshal(ListIssuesResponse{Issues: issues})
if err != nil {
return nil, err
}
return wrapperspb.Bytes(data), nil
}
if interceptor == nil {
return call(ctx)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: listIssuesMethod,
}
return interceptor(ctx, &ListIssuesRequest{}, info, func(ctx context.Context, _ any) (any, error) {
return call(ctx)
})
}
type Client struct {
conn *grpc.ClientConn
rpc pb.DaemonServiceClient
}
func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
creds, err := id.DialOption(target, presence.Daemon)
@@ -24,9 +105,23 @@ func Dial(target string, id *rpctls.Identity) (*Client, func(), error) {
if err != nil {
return nil, nil, err
}
return &Client{rpc: pb.NewDaemonServiceClient(conn)}, func() { _ = conn.Close() }, nil
return &Client{conn: conn, rpc: pb.NewDaemonServiceClient(conn)}, func() { _ = conn.Close() }, nil
}
func (c *Client) CheckRepository(ctx context.Context, r *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error) {
return c.rpc.CheckRepository(rpcidentity.Outgoing(ctx, presence.UI), r)
}
func (c *Client) ListIssues(ctx context.Context, _ *ListIssuesRequest) (*ListIssuesResponse, error) {
out := new(wrapperspb.BytesValue)
if err := c.conn.Invoke(rpcidentity.Outgoing(ctx, presence.UI), listIssuesMethod, wrapperspb.Bytes(nil), out); err != nil {
return nil, err
}
var resp ListIssuesResponse
if len(out.GetValue()) > 0 {
if err := json.Unmarshal(out.GetValue(), &resp); err != nil {
return nil, err
}
}
return &resp, nil
}
+43
View File
@@ -9,12 +9,55 @@ import (
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/daemon/v1"
"github.com/samcharles93/archie-core/internal/infrastructure/daemonrpc"
)
type RepositoryChecker interface {
CheckRepository(context.Context, *pb.CheckRepositoryRequest) (*pb.CheckRepositoryResponse, error)
}
type IssueLister interface {
ListIssues(context.Context, *daemonrpc.ListIssuesRequest) (*daemonrpc.ListIssuesResponse, error)
}
type issueView struct {
Owner string `json:"owner"`
Repository string `json:"repository"`
Number int32 `json:"number"`
Title string `json:"title"`
Labels []string `json:"labels,omitempty"`
}
func (s *Server) handleIssues(w http.ResponseWriter, r *http.Request) {
if s.Issues == nil {
writeJSON(w, []issueView{})
return
}
response, err := s.Issues.ListIssues(r.Context(), &daemonrpc.ListIssuesRequest{})
if err != nil {
code, message := http.StatusServiceUnavailable, "Repository issues are unavailable."
switch status.Code(err) {
case codes.PermissionDenied:
code, message = http.StatusForbidden, "You do not have permission to list issues."
case codes.Unauthenticated:
code, message = http.StatusUnauthorized, "Sign in before listing issues."
}
http.Error(w, message, code)
return
}
out := make([]issueView, 0, len(response.Issues))
for _, issue := range response.Issues {
out = append(out, issueView{
Owner: issue.Owner,
Repository: issue.Repository,
Number: issue.Number,
Title: issue.Title,
Labels: issue.Labels,
})
}
writeJSON(w, out)
}
func (s *Server) handleRepositoryCheck(w http.ResponseWriter, r *http.Request) {
if !s.authorizeTaskMutation(w, r) {
return
@@ -61,6 +61,7 @@ func TestHTTPPolicyCannotBeBypassed(t *testing.T) {
{"GET", "/api/harness/bindings"},
{"GET", "/api/harness/terminal"},
{"GET", "/api/identities"},
{"GET", "/api/issues"},
{"GET", "/api/logs"},
{"GET", "/api/repositories"},
{"GET", "/api/mappings"},
+1 -1
View File
@@ -438,7 +438,7 @@ func kindOf(path string) access.ResourceKind {
return access.KindBinding
case matchPrefix(path, "/api/sources"):
return access.KindSource
case matchPrefix(path, "/api/work-requests"), matchPrefix(path, "/api/repositories"):
case matchPrefix(path, "/api/work-requests"), matchPrefix(path, "/api/repositories"), matchPrefix(path, "/api/issues"):
return access.KindTask
}
return access.KindDashboard
+2
View File
@@ -33,6 +33,7 @@ import (
type Server struct {
RepositoryChecks RepositoryChecker
Issues IssueLister
Accounts identity.Accounts
accountRateLimit *ratelimit.Limiter
@@ -280,6 +281,7 @@ func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/usage", s.handleUsage)
mux.HandleFunc("GET /api/setup", s.handleSetup)
newWorkflowsAPI(s).register(mux)
mux.HandleFunc("GET /api/issues", s.handleIssues)
mux.HandleFunc("POST /api/control-plane/resources/repository-policies/check", s.handleRepositoryCheck)
mux.HandleFunc("GET /api/skills", instanceOnly(s.handleSkills))
mux.HandleFunc("GET /api/curators", instanceOnly(s.handleCurators))
+36 -37
View File
@@ -7,13 +7,16 @@ import { Clock, Mic, Pencil, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
import { applyCommand, isExactCommand } from "./commands";
import { applyCompletion, resolveCompletionKey } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import {
activeCompletionLabel,
activeTrigger,
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
composerCaret,
composerText,
editQueued,
isCommandMenuOpen,
@@ -110,17 +113,18 @@ function onInput(event: Event): void {
}
function choose(index: number): void {
const spec = commandMatches.value[index];
const item = commandMatches.value[index];
const input = field.value?.$el;
if (!spec || !input) return;
// Completing the command replaces the token the caret sits in, which is
if (!item || !input) return;
// Completing the token replaces what the caret sits in, which is
// decided by the same rule that found the matches.
const { text, cursor } = applyCommand(
const { text, cursor } = applyCompletion(
input.value,
input.selectionStart ?? input.value.length,
spec.command,
input.selectionStart ?? composerCaret.value ?? input.value.length,
item.insertText || item.command,
);
composerText.value = text;
composerCaret.value = cursor;
closeCommandMenu();
void nextTick(() => {
input.focus();
@@ -131,41 +135,35 @@ function choose(index: number): void {
function onKeydown(event: KeyboardEvent): void {
// Safari may end composition before delivering its confirming Enter.
if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return;
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value && commandMatches.value.length) {
// A command typed in full is sent rather than completed, so Enter never
// re-enters the command the palette was offering.
if (
event.key === "Enter" &&
plain &&
isExactCommand(commandSpecs.value, composerText.value)
) {
event.preventDefault();
const action = resolveCompletionKey({
key: event.key,
shiftKey: event.shiftKey,
ctrlKey: event.ctrlKey,
metaKey: event.metaKey,
altKey: event.altKey,
isComposing: event.isComposing,
keyCode: event.keyCode,
menuOpen: isCommandMenuOpen.value,
matchCount: commandMatches.value.length,
selection: commandSelection.value,
activeTrigger: activeTrigger.value,
composerText: composerText.value,
commandSpecs: commandSpecs.value,
});
if (action) {
event.preventDefault();
if (action.type === "submit") {
closeCommandMenu();
void sendMessage();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
moveCommandSelection(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
moveCommandSelection(-1);
return;
}
if (event.key === "Enter" && plain) {
event.preventDefault();
choose(commandSelection.value);
return;
}
if (event.key === "Escape") {
} else if (action.type === "move") {
moveCommandSelection(action.delta);
} else if (action.type === "select") {
choose(action.index);
} else if (action.type === "dismiss") {
// Consumed here: dismissing the palette must not also close the panel.
event.preventDefault();
closeCommandMenu();
return;
}
return;
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
@@ -229,6 +227,7 @@ function onKeydown(event: KeyboardEvent): void {
v-if="isCommandMenuOpen && commandMatches.length"
:matches="commandMatches"
:selection="commandSelection"
:label="activeCompletionLabel"
@choose="choose"
/>
+19 -10
View File
@@ -2,14 +2,23 @@
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import type { ChatCommandSpec } from "./state";
import type { CompletionItem } from "./commands";
/**
* The slash palette: the commands the server accepts, floating above the
* composer. It is the only command surface -- there is no second list anywhere
* in the panel -- so the arrow keys and the pointer both land here.
* The completion palette: slash commands and `#` issue references, floating
* above the composer. It is the only completion surface -- there is no second
* list anywhere in the panel -- so the arrow keys and the pointer both land here.
*/
const props = defineProps<{ matches: ChatCommandSpec[]; selection: number }>();
const props = withDefaults(
defineProps<{
matches: CompletionItem[];
selection: number;
label?: string;
}>(),
{
label: "Commands",
},
);
const emit = defineEmits<{ choose: [index: number] }>();
const menu = ref<HTMLElement | null>(null);
@@ -41,12 +50,12 @@ watch(
ref="menu"
id="slash-palette"
role="listbox"
aria-label="Commands"
:aria-label="label"
class="absolute inset-x-3 bottom-[calc(100%-0.25rem)] z-30 grid max-h-72 gap-0.5 overflow-auto rounded-lg border border-border-strong bg-popover p-1.5 shadow-md"
>
<button
v-for="(spec, index) in matches"
:key="spec.command"
v-for="(item, index) in matches"
:key="item.key || item.command"
type="button"
role="option"
:id="`slash-palette-option-${index}`"
@@ -55,8 +64,8 @@ watch(
@mousedown.prevent
@click="emit('choose', index)"
>
<code class="truncate text-foreground">{{ spec.command }}</code>
<span class="truncate">{{ spec.description || spec.usage || "" }}</span>
<code class="truncate text-foreground">{{ item.label || item.command }}</code>
<span class="truncate">{{ item.detail || item.description || item.usage || "" }}</span>
</button>
</div>
</template>
+257 -30
View File
@@ -1,57 +1,205 @@
import type { ChatCommandSpec } from "./state";
import type { ChatCommandSpec } from "./state.ts";
/**
* The slash palette's arithmetic, kept out of the composer so it is decided in
* one place rather than reconstructed from DOM positions twice.
* The composer completion palette's arithmetic, kept out of the component so
* trigger detection, filtering, keyboard navigation, and replacement are
* decided in one place rather than reconstructed from DOM positions.
*/
/** The command token the caret sits in: a slash word at the start or after a space. */
const OPEN_TOKEN = /(?:^|\s)\/([^\s]*)$/;
const ANY_TOKEN = /(?:^|\s)\/[^\s]*$/;
export type CompletionTrigger = "/" | "#" | (string & {});
/** One open issue offered by `#` completion in the composer. */
export interface ChatIssue {
owner?: string;
repository?: string;
number: number;
title: string;
labels?: string[];
}
/** One entry in the completion popover, regardless of which trigger opened it. */
export interface CompletionItem extends ChatCommandSpec {
key: string;
trigger: CompletionTrigger;
label: string;
detail: string;
insertText: string;
searchText: string;
issue?: ChatIssue;
}
/** A pluggable source of completions for a trigger character. */
export interface CompletionSource {
trigger: CompletionTrigger;
label: string;
items: CompletionItem[];
}
/** The active trigger token ending at the caret. */
export interface TriggerMatch {
trigger: CompletionTrigger;
query: string;
tokenStart: number;
tokenEnd: number;
}
/** How many matches the palette will show at once. */
const MAX_MATCHES = 8;
export const MAX_MATCHES = 8;
const DEFAULT_TRIGGERS: readonly CompletionTrigger[] = ["/", "#"];
/**
* matchesFor returns the commands worth offering for the text before the
* caret, matched on the command and its description together so a word from
* either finds it.
* detectTrigger finds an open trigger token ending at the caret: a trigger
* character at the start of the draft or immediately after whitespace (spaces,
* tabs, or newlines), with no whitespace between the trigger and the caret.
*/
export function detectTrigger(
value: string,
caret: number,
triggers: readonly CompletionTrigger[] = DEFAULT_TRIGGERS,
): TriggerMatch | null {
const clampedCaret = Math.max(0, Math.min(caret, value.length));
const before = value.slice(0, clampedCaret);
const tail = before.match(/[^\s]*$/);
const token = tail?.[0] ?? "";
if (!token) return null;
const trigger = token[0] as CompletionTrigger;
if (!triggers.includes(trigger)) return null;
const tokenStart = before.length - token.length;
return {
trigger,
query: token.slice(1),
tokenStart,
tokenEnd: clampedCaret,
};
}
/** Builds the `/` completion source from the server's slash command specs. */
export function commandCompletionSource(
specs: ChatCommandSpec[],
): CompletionSource {
return {
trigger: "/",
label: "Commands",
items: specs.map((spec) => ({
key: `command:${spec.command}`,
trigger: "/",
label: spec.command,
detail: spec.description || spec.usage || "",
insertText: spec.command,
searchText:
`${spec.command} ${spec.description ?? ""} ${spec.usage ?? ""}`.toLowerCase(),
command: spec.command,
description: spec.description,
usage: spec.usage,
})),
};
}
/** Builds the `#` completion source from open repository issues. */
export function issueCompletionSource(issues: ChatIssue[]): CompletionSource {
return {
trigger: "#",
label: "Issues",
items: issues.map((issue) => {
const ref = `#${issue.number}`;
const repo =
issue.owner && issue.repository
? `${issue.owner}/${issue.repository}`
: "";
const labels = issue.labels?.join(" ") ?? "";
return {
key: `issue:${repo ? `${repo}#` : ""}${issue.number}`,
trigger: "#",
label: ref,
detail: issue.title,
insertText: ref,
searchText:
`${ref} ${issue.number} ${issue.title} ${repo} ${labels}`.toLowerCase(),
command: ref,
description: issue.title,
issue,
};
}),
};
}
/**
* completionsFor resolves the active trigger at the caret against the registered
* completion sources and filters its items by the typed query.
*/
export function completionsFor(
sources: readonly CompletionSource[],
value: string,
caret: number,
): {
trigger: CompletionTrigger | null;
label: string;
items: CompletionItem[];
} {
const triggers = sources.length
? sources.map((source) => source.trigger)
: DEFAULT_TRIGGERS;
const detected = detectTrigger(value, caret, triggers);
if (!detected) {
return { trigger: null, label: "", items: [] };
}
const source = sources.find((entry) => entry.trigger === detected.trigger);
if (!source) {
return { trigger: detected.trigger, label: "", items: [] };
}
const query = detected.query.toLowerCase();
const items = source.items
.filter((item) => item.searchText.includes(query))
.slice(0, MAX_MATCHES);
return {
trigger: source.trigger,
label: source.label,
items,
};
}
/**
* matchesFor returns the completion items worth offering for the text before
* the caret across slash commands (`/`) and open issues (`#`).
*/
export function matchesFor(
specs: ChatCommandSpec[],
value: string,
caret: number,
): ChatCommandSpec[] {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return [];
const query = match[1].toLowerCase();
return specs
.filter((spec) =>
`${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES);
issues: ChatIssue[] = [],
): CompletionItem[] {
return completionsFor(
[commandCompletionSource(specs), issueCompletionSource(issues)],
value,
caret,
).items;
}
/**
* applyCommand replaces the token being completed with the chosen command and
* returns the cursor position just after it, ready for the next word.
* applyCompletion replaces the active trigger token ending at the caret with
* the chosen insertion text followed by a space, and returns the post-insertion
* cursor index.
*/
export function applyCommand(
export function applyCompletion(
value: string,
caret: number,
command: string,
insertText: string,
triggers: readonly CompletionTrigger[] = DEFAULT_TRIGGERS,
): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(ANY_TOKEN);
const tokenStart =
start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
const clampedCaret = Math.max(0, Math.min(caret, value.length));
const before = value.slice(0, clampedCaret);
const after = value.slice(clampedCaret);
const detected = detectTrigger(value, clampedCaret, triggers);
const tokenStart = detected ? detected.tokenStart : before.length;
return {
text: `${before.slice(0, tokenStart)}${command} ${after}`,
cursor: tokenStart + command.length + 1,
text: `${before.slice(0, tokenStart)}${insertText} ${after}`,
cursor: tokenStart + insertText.length + 1,
};
}
export const applyCommand = applyCompletion;
/**
* isExactCommand reports whether the composer already holds a command and
* nothing else. Enter then sends it rather than completing it, so a command
@@ -64,3 +212,82 @@ export function isExactCommand(
const trimmed = value.trim();
return specs.some((spec) => spec.command === trimmed);
}
/** Moves the active option index by delta with wrap-around. */
export function moveSelection(
current: number,
delta: number,
length: number,
): number {
if (length <= 0) return 0;
return (((current + delta) % length) + length) % length;
}
export type CompletionKeyAction =
| { type: "move"; delta: 1 | -1; selection: number }
| { type: "select"; index: number }
| { type: "dismiss" }
| { type: "submit" }
| null;
export interface CompletionKeyInput {
key: string;
shiftKey?: boolean;
ctrlKey?: boolean;
metaKey?: boolean;
altKey?: boolean;
isComposing?: boolean;
keyCode?: number;
menuOpen: boolean;
matchCount: number;
selection: number;
activeTrigger: CompletionTrigger | null;
composerText: string;
commandSpecs?: ChatCommandSpec[];
}
/**
* resolveCompletionKey decides how a keydown event interacts with the open
* completion popover. Returns null when the event is not handled by the menu.
*/
export function resolveCompletionKey(
input: CompletionKeyInput,
): CompletionKeyAction {
if (input.key === "Enter" && (input.isComposing || input.keyCode === 229)) {
return null;
}
if (!input.menuOpen || input.matchCount <= 0) {
return null;
}
const plain =
!input.shiftKey && !input.ctrlKey && !input.metaKey && !input.altKey;
if (
input.key === "Enter" &&
plain &&
input.activeTrigger === "/" &&
isExactCommand(input.commandSpecs ?? [], input.composerText)
) {
return { type: "submit" };
}
if (input.key === "ArrowDown") {
return {
type: "move",
delta: 1,
selection: moveSelection(input.selection, 1, input.matchCount),
};
}
if (input.key === "ArrowUp") {
return {
type: "move",
delta: -1,
selection: moveSelection(input.selection, -1, input.matchCount),
};
}
if ((input.key === "Enter" || input.key === "Tab") && plain) {
return { type: "select", index: input.selection };
}
if (input.key === "Escape") {
return { type: "dismiss" };
}
return null;
}
+64 -9
View File
@@ -3,7 +3,16 @@ import { onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { randomUUID } from "@/lib/uuid";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
import {
commandCompletionSource,
completionsFor,
detectTrigger,
issueCompletionSource,
moveSelection,
type ChatIssue,
type CompletionItem,
type CompletionTrigger,
} from "./commands";
import {
resolveTurn,
retryChatTurn,
@@ -35,6 +44,8 @@ export interface ChatCommandSpec {
description?: string;
}
export type { ChatIssue, CompletionItem, CompletionTrigger };
/**
* A tool the assistant called. A live frame names the tool in `tool` and
* carries its outcome in `text`; a recorded turn uses `name` and `summary`.
@@ -208,9 +219,13 @@ export const selectorData = ref<ChatSelectorData>({});
export const selectedModel = ref("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const issueSpecs = ref<ChatIssue[]>([]);
export const commandMatches = ref<CompletionItem[]>([]);
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
export const activeTrigger = ref<CompletionTrigger | null>(null);
export const activeCompletionLabel = ref("Commands");
export const composerCaret = ref(0);
/**
* How many layers inside the panel currently own Escape -- an open popover, a
@@ -502,11 +517,48 @@ export function editQueued(index: number): void {
composerText.value = composerText.value.trim() ? `${composerText.value}\n${text}` : text;
}
/** Opens the palette for the slash word the caret sits in, or closes it. */
let issuesRequest: Promise<void> | null = null;
export async function refreshIssues(): Promise<void> {
if (issuesRequest) return issuesRequest;
issuesRequest = api
.issues<ChatIssue[]>()
.then((items) => {
issueSpecs.value = Array.isArray(items) ? items : [];
if (
detectTrigger(composerText.value, composerCaret.value)?.trigger === "#"
) {
syncCommandMenu(composerText.value, composerCaret.value);
}
})
.catch(() => {
// Issues are optional context; leave the list empty if unavailable.
})
.finally(() => {
issuesRequest = null;
});
return issuesRequest;
}
/** Opens the palette for the trigger token the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
const matches = matchesFor(commandSpecs.value, value, caret);
if (matches.length) {
commandMatches.value = matches;
composerCaret.value = caret;
const detected = detectTrigger(value, caret);
if (detected?.trigger === "#" && issueSpecs.value.length === 0) {
void refreshIssues();
}
const result = completionsFor(
[
commandCompletionSource(commandSpecs.value),
issueCompletionSource(issueSpecs.value),
],
value,
caret,
);
activeTrigger.value = result.trigger;
if (result.items.length) {
activeCompletionLabel.value = result.label;
commandMatches.value = result.items;
commandSelection.value = 0;
isCommandMenuOpen.value = true;
return;
@@ -517,12 +569,15 @@ export function syncCommandMenu(value: string, caret: number): void {
export function closeCommandMenu(): void {
isCommandMenuOpen.value = false;
activeTrigger.value = null;
}
export function moveCommandSelection(delta: number): void {
const length = commandMatches.value.length;
if (!length) return;
commandSelection.value = (commandSelection.value + delta + length) % length;
commandSelection.value = moveSelection(
commandSelection.value,
delta,
commandMatches.value.length,
);
}
/** The page the operator asked from, so an answer can be about what they saw. */
+1
View File
@@ -314,6 +314,7 @@ export const api = {
}),
checkRepository: <T = unknown>(input: { owner: string; repository: string; identity_id: string }) => request<T>("/api/control-plane/resources/repository-policies/check", { method: "POST", body: input, timeoutMs: 35000 }),
repositories: <T = unknown>() => request<T>("/api/repositories"),
issues: <T = unknown>() => request<T>("/api/issues"),
workRequest: <T = unknown>(workRequest: Payload) =>
request<T>("/api/work-requests", { method: "POST", body: workRequest }),
skills: <T = unknown>() => request<T>("/api/skills"),
+266
View File
@@ -0,0 +1,266 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
applyCommand,
applyCompletion,
commandCompletionSource,
completionsFor,
detectTrigger,
isExactCommand,
issueCompletionSource,
matchesFor,
MAX_MATCHES,
moveSelection,
resolveCompletionKey,
type ChatIssue,
type CompletionSource,
} from "../src/chat/commands.ts";
import type { ChatCommandSpec } from "../src/chat/state.ts";
const sampleCommands: ChatCommandSpec[] = [
{ command: "/help", description: "List available commands" },
{ command: "/model", description: "Switch active model" },
{ command: "/new", description: "Start a fresh conversation" },
];
const sampleIssues: ChatIssue[] = [
{
owner: "sam",
repository: "archie",
number: 1861,
title: "Chat composer: '#' context dropdown for issues",
labels: ["ui", "chat"],
},
{
owner: "sam",
repository: "archie",
number: 1842,
title: "Retry stalled task runs from the board",
labels: ["tasks"],
},
{
owner: "acme",
repository: "ops",
number: 99,
title: "Rotate webhook signing secret",
},
];
test("detectTrigger matches trigger characters at start of input or after whitespace", () => {
assert.deepEqual(detectTrigger("#", 1), {
trigger: "#",
query: "",
tokenStart: 0,
tokenEnd: 1,
});
assert.deepEqual(detectTrigger("#1861", 5), {
trigger: "#",
query: "1861",
tokenStart: 0,
tokenEnd: 5,
});
assert.deepEqual(detectTrigger("Implement #186", 14), {
trigger: "#",
query: "186",
tokenStart: 10,
tokenEnd: 14,
});
assert.deepEqual(detectTrigger("First line\n#dropdown", 20), {
trigger: "#",
query: "dropdown",
tokenStart: 11,
tokenEnd: 20,
});
assert.deepEqual(detectTrigger("Fix #18 in composer", 7), {
trigger: "#",
query: "18",
tokenStart: 4,
tokenEnd: 7,
});
assert.deepEqual(detectTrigger("/mod", 4), {
trigger: "/",
query: "mod",
tokenStart: 0,
tokenEnd: 4,
});
// Mid-word '#' or closed tokens followed by whitespace do not trigger.
assert.equal(detectTrigger("issue#1861", 10), null);
assert.equal(detectTrigger("#1861 ", 6), null);
assert.equal(detectTrigger("", 0), null);
// Pluggable custom triggers work with the same detector.
assert.deepEqual(detectTrigger("assign @arc", 11, ["/", "#", "@"]), {
trigger: "@",
query: "arc",
tokenStart: 7,
tokenEnd: 11,
});
});
test("completionsFor and matchesFor filter open issues and slash commands", () => {
const allIssues = matchesFor(sampleCommands, "Check #", 7, sampleIssues);
assert.deepEqual(
allIssues.map((item) => [item.label, item.detail, item.insertText]),
[
["#1861", "Chat composer: '#' context dropdown for issues", "#1861"],
["#1842", "Retry stalled task runs from the board", "#1842"],
["#99", "Rotate webhook signing secret", "#99"],
],
);
const byNumber = matchesFor(sampleCommands, "See #186", 8, sampleIssues);
assert.deepEqual(
byNumber.map((item) => item.label),
["#1861"],
);
const byTitle = matchesFor(
sampleCommands,
"Investigate #DROPDOWN",
21,
sampleIssues,
);
assert.deepEqual(
byTitle.map((item) => item.label),
["#1861"],
);
const byRepo = matchesFor(sampleCommands, "In #acme/ops", 12, sampleIssues);
assert.deepEqual(
byRepo.map((item) => item.label),
["#99"],
);
const commands = matchesFor(sampleCommands, "/mo", 3, sampleIssues);
assert.deepEqual(
commands.map((item) => item.label),
["/model"],
);
const manyIssues: ChatIssue[] = Array.from({ length: 12 }, (_, index) => ({
number: index + 1,
title: `Issue ${index + 1}`,
}));
const capped = matchesFor(sampleCommands, "#", 1, manyIssues);
assert.equal(capped.length, MAX_MATCHES);
// Pluggable completion source alongside '/' and '#'
const workflowSource: CompletionSource = {
trigger: "@",
label: "Workflows",
items: [
{
key: "workflow:triage",
trigger: "@",
label: "@triage",
detail: "Triage incoming issues",
insertText: "@triage",
searchText: "@triage triage incoming issues",
command: "@triage",
},
],
};
const custom = completionsFor(
[
commandCompletionSource(sampleCommands),
issueCompletionSource(sampleIssues),
workflowSource,
],
"Run @tri",
8,
);
assert.equal(custom.trigger, "@");
assert.equal(custom.label, "Workflows");
assert.deepEqual(
custom.items.map((item) => item.insertText),
["@triage"],
);
});
test("applyCompletion replaces the active trigger token and places the caret after the trailing space", () => {
assert.deepEqual(applyCompletion("#18", 3, "#1861"), {
text: "#1861 ",
cursor: 6,
});
assert.deepEqual(applyCompletion("Implement #186 now", 14, "#1861"), {
text: "Implement #1861 now",
cursor: 16,
});
assert.deepEqual(applyCompletion("Line one\n#drop", 14, "#1861"), {
text: "Line one\n#1861 ",
cursor: 15,
});
assert.deepEqual(applyCommand("/he", 3, "/help"), {
text: "/help ",
cursor: 6,
});
});
test("keyboard navigation wraps selection, accepts with Enter or Tab, and dismisses with Escape", () => {
assert.equal(moveSelection(0, 1, 3), 1);
assert.equal(moveSelection(2, 1, 3), 0);
assert.equal(moveSelection(0, -1, 3), 2);
assert.equal(moveSelection(0, 1, 0), 0);
const baseInput = {
menuOpen: true,
matchCount: 3,
selection: 1,
activeTrigger: "#" as const,
composerText: "Implement #18",
commandSpecs: sampleCommands,
};
assert.deepEqual(
resolveCompletionKey({ ...baseInput, key: "ArrowDown" }),
{ type: "move", delta: 1, selection: 2 },
);
assert.deepEqual(
resolveCompletionKey({ ...baseInput, selection: 0, key: "ArrowUp" }),
{ type: "move", delta: -1, selection: 2 },
);
assert.deepEqual(
resolveCompletionKey({ ...baseInput, key: "Enter" }),
{ type: "select", index: 1 },
);
assert.deepEqual(
resolveCompletionKey({ ...baseInput, key: "Tab" }),
{ type: "select", index: 1 },
);
assert.deepEqual(
resolveCompletionKey({ ...baseInput, key: "Escape" }),
{ type: "dismiss" },
);
// Shift+Enter or IME composition should not select an item.
assert.equal(
resolveCompletionKey({ ...baseInput, key: "Enter", shiftKey: true }),
null,
);
assert.equal(
resolveCompletionKey({ ...baseInput, key: "Enter", isComposing: true }),
null,
);
// Exact slash command submits on Enter instead of re-completing.
assert.equal(isExactCommand(sampleCommands, "/help"), true);
assert.deepEqual(
resolveCompletionKey({
...baseInput,
activeTrigger: "/",
composerText: "/help",
key: "Enter",
}),
{ type: "submit" },
);
});