From 23f72fc46da3b2a8f8b868af2e8435082daabe91 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Mon, 16 Nov 2026 10:31:20 +0800 Subject: [PATCH] feat: switch model or agent and start new sessions - chat: a searchable sheet picks the model or agent for the session; the choice is applied through the server and mirrored in the session list - sessions: a new-session sheet with a title and a working directory (the server's default plus the directories already listed); creating one opens its chat - ocapi: list models with their display names and read the server's default location - bump version to 0.1.1 (build 2) --- PLAN.md | 4 +- README.md | 7 +- asuka.json | 4 +- internal/appui/chat.go | 170 +++++++++++++++++++++++++++++ internal/appui/chat_test.go | 97 +++++++++++++++- internal/appui/root.go | 65 +++++++---- internal/appui/screens.go | 10 +- internal/appui/sessions_actions.go | 102 +++++++++++++++++ internal/ocapi/sessions.go | 44 ++++++-- 9 files changed, 461 insertions(+), 42 deletions(-) diff --git a/PLAN.md b/PLAN.md index d0fead3..513decb 100644 --- a/PLAN.md +++ b/PLAN.md @@ -39,7 +39,9 @@ M0 完成,并继续做到了 M3。所有验证都连的是本机正在运行 | release 构建 | `asuka build -p android` 产出 `dist/OpenChamber.aab`;合并后的 release manifest 含 `usesCleartextTraffic="true"`(由 `netcfg` 模块合入),明文 HTTP 在 release 可用 | | 会话操作 | 滑动归档/删除、长按菜单、重命名(Alert 输入框)、删除二次确认 | | 权限审批 | 聊天页内联卡片(允许一次/总是允许/拒绝),启动时补齐待批列表,SSE 实时增删 | -| 下一步 | M4 余项:模型/Agent 切换、新建会话;M5:Android 真机 + release 明文 HTTP | +| 模型/Agent | 聊天页顶栏打开选择 Sheet(可搜索),切换后同步会话列表 | +| 新建会话 | 会话页「新建」:标题 + 工作目录(服务端默认目录与已加载会话的目录),创建后直接进入聊天 | +| 下一步 | 打磨:图标/splash、中英 i18n、空态与错误页;可选 fork asuka 支持更低 minSdk | **明文 HTTP 的落地方式**(用户已确认 release 也要支持):native 包 `netcfg` 已加入(`main.go` 里空白导入),Gradle 会把它的 manifest 合并进 release。已实测 release 的合并 manifest 含 `usesCleartextTraffic="true"`,并用 release APK 连上了 `http://10.0.2.2:3000`: diff --git a/README.md b/README.md index f3a223d..b6dc15c 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,10 @@ A lightweight OpenChamber client for phones, written in Go with [Asuka](https://asuka.egoist.dev/)'s native widgets. Android first. -Status: M0–M3 done, M4 in progress — connect (password / passwordless, HTTP or -SOCKS5 proxy, self-signed certificates), live session list, chat with streaming -Markdown, permissions, archive/delete/rename, and a UI-independent API client. +Status: M0–M4 done — connect (password / passwordless, HTTP or SOCKS5 proxy, +self-signed certificates), live session list, chat with streaming Markdown, +permissions, model/agent switching, new sessions, archive/delete/rename, and a +UI-independent API client. ## What is here diff --git a/asuka.json b/asuka.json index da55d3a..d8797a1 100644 --- a/asuka.json +++ b/asuka.json @@ -1,7 +1,7 @@ { "name": "OpenChamber", "id": "com.openchamber.native", - "version": "0.1.0", - "build": 1, + "version": "0.1.1", + "build": 2, "orientations": ["portrait", "landscape"] } diff --git a/internal/appui/chat.go b/internal/appui/chat.go index 15ba6e5..2c46669 100644 --- a/internal/appui/chat.go +++ b/internal/appui/chat.go @@ -53,6 +53,21 @@ type chat struct { reasoningSlots map[string]map[int]int reloadScheduled bool listNode ui.Node + + pickerOpen *signal.Signal[bool] + pickerKind string + pickerItems *signal.Signal[[]pickerItem] + pickerFilter *signal.Signal[string] + pickerLoad *signal.Signal[bool] +} + +// pickerItem is one row of the model/agent sheet. +type pickerItem struct { + Key string + Title string + Subtitle string + Model *ocapi.ModelRef + Agent string } func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat { @@ -76,6 +91,10 @@ func (c *controller) openChat(s *ocapi.Session, nav *ui.Navigator) *chat { errText: signal.New(""), textSlots: map[string]map[int]int{}, reasoningSlots: map[string]map[int]int{}, + pickerOpen: signal.New(false), + pickerItems: signal.NewFunc([]pickerItem{}, nil), + pickerFilter: signal.New(""), + pickerLoad: signal.New(false), } c.chat = ch ch.load() @@ -417,9 +436,160 @@ func (ch *chat) screen() ui.Node { ch.permissionSection(), ch.composer(), ), + ui.Sheet(ui.SheetProps{ + Open: ch.pickerOpen, + Detents: ui.DetentLarge, + Grabber: true, + Content: ch.pickerSheet, + OnDismiss: func() { ch.pickerOpen.Set(false) }, + }), ) } +func (ch *chat) openModelPicker() { + ch.openPicker("model") +} + +func (ch *chat) openAgentPicker() { + ch.openPicker("agent") +} + +func (ch *chat) openPicker(kind string) { + client := ch.client() + if client == nil { + return + } + ch.pickerKind = kind + ch.pickerFilter.Set("") + ch.pickerItems.Set(nil) + ch.pickerLoad.Set(true) + ch.pickerOpen.Set(true) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var items []pickerItem + var err error + switch kind { + case "model": + var models []ocapi.ModelInfo + models, err = client.Models(ctx, ch.dir) + for _, m := range models { + name := m.Name + if name == "" { + name = m.ID + } + items = append(items, pickerItem{ + Key: m.ProviderID + "/" + m.ID, + Title: name, + Subtitle: m.ProviderID + " · " + m.ID, + Model: &ocapi.ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant}, + }) + } + case "agent": + var agents []ocapi.AgentInfo + agents, err = client.Agents(ctx, ch.dir) + for _, a := range agents { + if a.Hidden { + continue + } + items = append(items, pickerItem{ + Key: a.ID, + Title: a.Name, + Subtitle: a.Description, + Agent: a.ID, + }) + } + } + ui.Post(func() { + ch.pickerLoad.Set(false) + if err != nil { + ch.errText.Set(friendlyError(err)) + return + } + ch.pickerItems.Set(items) + }) + }() +} + +func (ch *chat) filteredPicks() signal.Accessor[[]pickerItem] { + return signal.Func(func() []pickerItem { + q := strings.ToLower(strings.TrimSpace(ch.pickerFilter.Get())) + items := ch.pickerItems.Get() + if q == "" { + return items + } + out := make([]pickerItem, 0, len(items)) + for _, it := range items { + if strings.Contains(strings.ToLower(it.Title), q) || + strings.Contains(strings.ToLower(it.Subtitle), q) { + out = append(out, it) + } + } + return out + }) +} + +func (ch *chat) pickerSheet() ui.Node { + title := "选择模型" + if ch.pickerKind == "agent" { + title = "选择 Agent" + } + return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 12, Grow: 1}, + ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}), + ui.TextField(ui.TextFieldProps{ + Value: ch.pickerFilter, + Placeholder: ui.Val("搜索"), + Style: ui.Style{Grow: 0}, + }), + ui.Show(ch.pickerLoad, func() ui.Node { + return ui.Activity() + }), + ui.List(ui.ListProps{Appearance: ui.ListPlain, Style: ui.Style{Grow: 1}}, + ch.filteredPicks(), func(it pickerItem) string { return it.Key }, + func(it signal.Accessor[pickerItem], _ signal.Accessor[int]) ui.Node { + return ui.View(ui.ViewProps{OnPress: func() { ch.applyPick(it.Get()) }, + Style: ui.Style{Padding: ui.Symmetric(10, 4), Gap: 2}}, + ui.Text(signal.Func(func() string { return it.Get().Title }), ui.Style{Font: fonts.Headline, Lines: 1}), + ui.Show(signal.Func(func() bool { return it.Get().Subtitle != "" }), + func() ui.Node { + return ui.Text(signal.Func(func() string { return it.Get().Subtitle }), + ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 2}) + }), + ) + }), + ) +} + +func (ch *chat) applyPick(it pickerItem) { + ch.pickerOpen.Set(false) + client := ch.client() + if client == nil { + return + } + kind := ch.pickerKind + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + var err error + if kind == "model" && it.Model != nil { + err = client.SwitchModel(ctx, ch.id, ch.dir, *it.Model) + } else if it.Agent != "" { + err = client.SwitchAgent(ctx, ch.id, ch.dir, it.Agent) + } + ui.Post(func() { + if err != nil { + ch.errText.Set(friendlyError(err)) + return + } + if kind == "model" && it.Model != nil { + ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Model = it.Model }) + } else if it.Agent != "" { + ch.c.patchSession(ch.id, func(s *ocapi.Session) { s.Agent = it.Agent }) + } + }) + }() +} + // perms are the pending permission requests for this session. func (ch *chat) perms() signal.Accessor[[]ocapi.PermissionRequest] { return signal.Func(func() []ocapi.PermissionRequest { diff --git a/internal/appui/chat_test.go b/internal/appui/chat_test.go index 8b2d09d..365a8ad 100644 --- a/internal/appui/chat_test.go +++ b/internal/appui/chat_test.go @@ -19,6 +19,8 @@ type chatServer struct { *httptest.Server prompts chan map[string]any replies chan map[string]any + models chan map[string]any + created chan map[string]any events chan string ready chan struct{} readyOne sync.Once @@ -37,6 +39,8 @@ func newChatServer(t *testing.T) *chatServer { cs := &chatServer{ prompts: make(chan map[string]any, 1), replies: make(chan map[string]any, 1), + models: make(chan map[string]any, 1), + created: make(chan map[string]any, 1), events: make(chan string, 8), ready: make(chan struct{}), } @@ -47,10 +51,6 @@ func newChatServer(t *testing.T) *chatServer { mux.HandleFunc("/auth/session", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"authenticated":true,"disabled":true}`) }) - mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2}, - "location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`) - }) mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"data":{}}`) }) @@ -64,6 +64,9 @@ func newChatServer(t *testing.T) *chatServer { "content":[{"type":"text","text":"**Hello** from the agent"}]} ],"cursor":{}}`) }) + mux.HandleFunc("/api/session/ses_new/message", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"data":[],"cursor":{}}`) + }) mux.HandleFunc("/api/session/ses_1/prompt", func(w http.ResponseWriter, r *http.Request) { var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) @@ -75,6 +78,41 @@ func newChatServer(t *testing.T) *chatServer { cs.events <- `{"id":"evt_3","created":101,"type":"session.text.delta","data":{"sessionID":"ses_1","assistantMessageID":"msg_stream","ordinal":0,"delta":"streamed"}}` fmt.Fprint(w, `{"data":{}}`) }) + mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`) + }) + mux.HandleFunc("/api/model", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"data":[ + {"id":"gpt-4","providerID":"openai","name":"GPT-4"}, + {"id":"claude","providerID":"anthropic","name":"Claude"}]}`) + }) + mux.HandleFunc("/api/agent", func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"data":[{"id":"build","name":"Build"},{"id":"plan","name":"Plan"}]}`) + }) + mux.HandleFunc("/api/session/ses_1/model", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + select { + case cs.models <- body: + default: + } + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + fmt.Fprint(w, `{"data":[{"id":"ses_1","title":"First session","time":{"created":1,"updated":2}, + "location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + select { + case cs.created <- body: + default: + } + fmt.Fprint(w, `{"data":{"id":"ses_new","title":"New chat","time":{"created":3,"updated":3}, + "location":{"directory":"/home/me/project"}}}`) + }) mux.HandleFunc("/api/session/ses_1/permission/per_1/reply", func(w http.ResponseWriter, r *http.Request) { var body map[string]any _ = json.NewDecoder(r.Body).Decode(&body) @@ -174,3 +212,54 @@ func TestPermissionCardAndReply(t *testing.T) { t.Fatal("no permission reply reached the server") } } + +func TestSwitchModel(t *testing.T) { + srv := newChatServer(t) + a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid)) + a.Type("http://192.168.1.5:3000", srv.URL) + a.Tap("连接") + a.WaitFor("First session") + a.Tap("First session") + a.WaitFor("Hello from the agent") + + a.Tap("模型") + a.WaitFor("GPT-4") + a.Tap("GPT-4") + + select { + case body := <-srv.models: + model, _ := body["model"].(map[string]any) + if model["id"] != "gpt-4" || model["providerID"] != "openai" { + t.Errorf("model switch = %v", body) + } + case <-time.After(3 * time.Second): + t.Fatal("no model switch reached the server") + } +} + +func TestCreateSession(t *testing.T) { + srv := newChatServer(t) + a := uitest.Mount(t, func() ui.Node { return rootWithStore(&memStore{}) }, uitest.Platform(ui.PlatformAndroid)) + a.Type("http://192.168.1.5:3000", srv.URL) + a.Tap("连接") + a.WaitFor("First session") + + a.Tap("新建") + a.WaitFor("新建会话") + a.Type("标题(可选,留空由服务端生成)", "Test chat") + a.Tap("创建") + a.WaitFor("New chat") + + select { + case body := <-srv.created: + if body["title"] != "Test chat" { + t.Errorf("created title = %v", body["title"]) + } + loc, _ := body["location"].(map[string]any) + if loc["directory"] != "/home/me/project" { + t.Errorf("created location = %v", body["location"]) + } + case <-time.After(3 * time.Second): + t.Fatal("no create request reached the server") + } +} diff --git a/internal/appui/root.go b/internal/appui/root.go index 349a844..0745d17 100644 --- a/internal/appui/root.go +++ b/internal/appui/root.go @@ -29,12 +29,20 @@ func newApp(st storage.Store) (*controller, ui.Node) { signal.OnCleanup(c.shutdown) node := ui.Stack(c.screen, ui.ScreenOptions{ Title: ui.Val("OpenChamber"), - Actions: []ui.Action{{ - Title: ui.Val("刷新"), - Icon: ui.IconRefresh, - Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }), - OnPress: c.refresh, - }}, + Actions: []ui.Action{ + { + Title: ui.Val("新建"), + Icon: ui.IconPlus, + Disabled: signal.Func(func() bool { return !c.connected.Get() }), + OnPress: c.openNewSession, + }, + { + Title: ui.Val("刷新"), + Icon: ui.IconRefresh, + Disabled: signal.Func(func() bool { return !c.connected.Get() || c.busy.Get() }), + OnPress: c.refresh, + }, + }, }) return c, node } @@ -56,26 +64,39 @@ type controller struct { active *signal.Signal[map[string]bool] perms *signal.Signal[[]ocapi.PermissionRequest] + defaultDir *signal.Signal[string] + + newOpen *signal.Signal[bool] + newTitle *signal.Signal[string] + newDir *signal.Signal[int] + creating *signal.Signal[bool] + client *ocapi.Client cancelSSE context.CancelFunc chat *chat + nav *ui.Navigator } func newController(st storage.Store) *controller { c := &controller{ - st: st, - url: signal.New(""), - password: signal.New(""), - useProxy: signal.New(false), - proxy: signal.New(""), - insecure: signal.New(false), - status: signal.New("输入服务器地址与密码后连接"), - server: signal.New(""), - connected: signal.New(false), - busy: signal.New(false), - sessions: signal.NewFunc([]ocapi.Session{}, nil), - active: signal.NewFunc(map[string]bool{}, nil), - perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil), + st: st, + url: signal.New(""), + password: signal.New(""), + useProxy: signal.New(false), + proxy: signal.New(""), + insecure: signal.New(false), + status: signal.New("输入服务器地址与密码后连接"), + server: signal.New(""), + connected: signal.New(false), + busy: signal.New(false), + sessions: signal.NewFunc([]ocapi.Session{}, nil), + active: signal.NewFunc(map[string]bool{}, nil), + perms: signal.NewFunc([]ocapi.PermissionRequest{}, nil), + defaultDir: signal.New(""), + newOpen: signal.New(false), + newTitle: signal.New(""), + newDir: signal.New(0), + creating: signal.New(false), } if conn, ok := st.Connection(); ok { c.url.Set(conn.URL) @@ -229,6 +250,9 @@ func (c *controller) establish(p connectParams, token string) { return } + if loc, err := client.Location(ctx); err == nil && loc.Directory != "" { + ui.Post(func() { c.defaultDir.Set(loc.Directory) }) + } page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"}) if err != nil { fail(err) @@ -276,6 +300,9 @@ func (c *controller) refresh() { go func() { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() + if loc, err := client.Location(ctx); err == nil && loc.Directory != "" { + ui.Post(func() { c.defaultDir.Set(loc.Directory) }) + } page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: 50, Order: "desc"}) active, aerr := client.ActiveSessions(ctx) running := make(map[string]bool, len(active)) diff --git a/internal/appui/screens.go b/internal/appui/screens.go index 81d5035..d6b48a4 100644 --- a/internal/appui/screens.go +++ b/internal/appui/screens.go @@ -65,6 +65,7 @@ func (c *controller) connectScreen() ui.Node { func (c *controller) sessionsScreen() ui.Node { nav := ui.UseNavigator() + c.nav = nav return ui.Column(ui.Style{Grow: 1}, ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 8, Align: ui.AlignCenter}, ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1, Grow: 1}), @@ -97,11 +98,18 @@ func (c *controller) sessionsScreen() ui.Node { OnPress: func() { sess := s.Get() ch := c.openChat(&sess, nav) - nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title}) + nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)}) }, OnLongPress: func() { c.sessionMenu(s.Get()) }, }, c.sessionRow(s, idx)) }), + ui.Sheet(ui.SheetProps{ + Open: c.newOpen, + Detents: ui.DetentLarge, + Grabber: true, + Content: c.newSessionSheet, + OnDismiss: func() { c.creating.Set(false) }, + }), ) } diff --git a/internal/appui/sessions_actions.go b/internal/appui/sessions_actions.go index 9e98b8f..f149f9f 100644 --- a/internal/appui/sessions_actions.go +++ b/internal/appui/sessions_actions.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/egoist/asuka/fonts" "github.com/egoist/asuka/signal" "github.com/egoist/asuka/ui" "github.com/openchamber/openchamber-native/internal/ocapi" @@ -127,3 +128,104 @@ func sessionDir(s ocapi.Session) string { } return "" } + +// directories lists the working directories a new session can use: the +// server's default, then every directory the loaded sessions live in. +func (c *controller) directories() signal.Accessor[[]string] { + return signal.Func(func() []string { + seen := map[string]bool{} + out := make([]string, 0, 4) + add := func(d string) { + if d == "" || seen[d] { + return + } + seen[d] = true + out = append(out, d) + } + add(c.defaultDir.Get()) + for _, s := range c.sessions.Get() { + if s.Location != nil { + add(s.Location.Directory) + } + } + return out + }) +} + +func chatActions(ch *chat) []ui.Action { + return []ui.Action{ + {Title: ui.Val("模型"), OnPress: ch.openModelPicker}, + {Title: ui.Val("Agent"), OnPress: ch.openAgentPicker}, + } +} + +func (c *controller) openNewSession() { + if c.client == nil { + return + } + c.newTitle.Set("") + c.newDir.Set(0) + c.creating.Set(false) + c.newOpen.Set(true) +} + +func (c *controller) newSessionSheet() ui.Node { + return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14, Grow: 1}, + ui.StaticText("新建会话", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}), + ui.TextField(ui.TextFieldProps{ + Value: c.newTitle, + Placeholder: ui.Val("标题(可选,留空由服务端生成)"), + ReturnKey: ui.ReturnGo, + OnSubmit: c.createSession, + }), + ui.Picker(ui.PickerProps{ + Items: c.directories(), + Selected: c.newDir, + Label: ui.Val("工作目录"), + }), + ui.Button(ui.ButtonProps{ + Title: ui.Val("创建"), + Variant: ui.ButtonFilled, + Disabled: c.creating, + OnPress: c.createSession, + }), + ui.Show(c.creating, func() ui.Node { return ui.Activity() }), + ) +} + +func (c *controller) createSession() { + client := c.client + nav := c.nav + if client == nil || c.creating.Peek() { + return + } + dirs := signal.Untrack(func() []string { return c.directories().Get() }) + dir := "" + if idx := c.newDir.Peek(); idx >= 0 && idx < len(dirs) { + dir = dirs[idx] + } + title := strings.TrimSpace(c.newTitle.Peek()) + c.creating.Set(true) + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) + defer cancel() + s, err := client.CreateSession(ctx, ocapi.CreateSessionOptions{Directory: dir, Title: title}) + ui.Post(func() { + c.creating.Set(false) + if err != nil { + c.status.Set(friendlyError(err)) + return + } + c.newOpen.Set(false) + c.sessions.Update(func(list []ocapi.Session) []ocapi.Session { + next := make([]ocapi.Session, 0, len(list)+1) + next = append(next, s) + return append(next, list...) + }) + if nav != nil { + ch := c.openChat(&s, nav) + nav.Push(ch.screen, ui.ScreenOptions{Title: ch.title, Actions: chatActions(ch)}) + } + }) + }() +} diff --git a/internal/ocapi/sessions.go b/internal/ocapi/sessions.go index 6f04f98..b6e73b2 100644 --- a/internal/ocapi/sessions.go +++ b/internal/ocapi/sessions.go @@ -149,28 +149,48 @@ func (c *Client) ListMessages(ctx context.Context, id string, o ListMessagesOpti return page, err } -// ModelSelection lists the models the server offers for a directory. -func (c *Client) Models(ctx context.Context, directory string) ([]ModelRef, error) { +// ModelInfo is one model the server offers. +type ModelInfo struct { + ID string `json:"id"` + ProviderID string `json:"providerID"` + Name string `json:"name"` + Variant string `json:"variant"` +} + +// Models lists the models the server offers for a directory. +func (c *Client) Models(ctx context.Context, directory string) ([]ModelInfo, error) { q := url.Values{} if directory != "" { q.Set("location[directory]", directory) } var payload struct { - Data []struct { - ID string `json:"id"` - ProviderID string `json:"providerID"` - Name string `json:"name"` - Variant string `json:"variant"` - } `json:"data"` + Data []ModelInfo `json:"data"` } if err := c.do(ctx, http.MethodGet, "/api/model", requestOptions{query: q}, nil, &payload); err != nil { return nil, err } - out := make([]ModelRef, 0, len(payload.Data)) - for _, m := range payload.Data { - out = append(out, ModelRef{ID: m.ID, ProviderID: m.ProviderID, Variant: m.Variant}) + return payload.Data, nil +} + +// ServerLocation is the server's default working directory. +type ServerLocation struct { + Directory string `json:"directory"` + ProjectID string `json:"projectID"` +} + +// Location reads the server's default location, which a new session uses +// when the user does not pick one. +func (c *Client) Location(ctx context.Context) (ServerLocation, error) { + var payload struct { + Directory string `json:"directory"` + Project struct { + ID string `json:"id"` + } `json:"project"` } - return out, nil + if err := c.do(ctx, http.MethodGet, "/api/location", requestOptions{}, nil, &payload); err != nil { + return ServerLocation{}, err + } + return ServerLocation{Directory: payload.Directory, ProjectID: payload.Project.ID}, nil } // AgentInfo is one entry of GET /api/agent.