feat: save several servers and pick one to connect
Match the first-party mobile client's connection screen: - the first screen lists saved servers, the one last used leading with its connect button or connected state, the others below, and adding is one tap - servers can be added, edited (name, address, proxy, self-signed) and deleted; deleting the live or last one returns to the list - a password sheet prompts only when the server asks for one, keeps the error and the typed password for a retry - while connected, the instances sheet switches servers - proxy and self-signed options stay per server (the native app's own) - the single-server record and its token migrate automatically - permission cards read a plain signal, fixing a flaky update - bump version to 0.1.2 (build 3)
This commit is contained in:
1 parent
ef0b63ceee
commit
13aca21d99
12 files changed
+966
-361
No files matched your search
+25
-13
@@ -54,6 +54,9 @@ type chat struct {
|
||||
reloadScheduled bool
|
||||
listNode ui.Node
|
||||
|
||||
permList *signal.Signal[[]ocapi.PermissionRequest]
|
||||
hasPerms *signal.Signal[bool]
|
||||
|
||||
pickerOpen *signal.Signal[bool]
|
||||
pickerKind string
|
||||
pickerItems *signal.Signal[[]pickerItem]
|
||||
@@ -91,12 +94,15 @@ 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{},
|
||||
permList: signal.NewFunc([]ocapi.PermissionRequest{}, nil),
|
||||
hasPerms: signal.New(false),
|
||||
pickerOpen: signal.New(false),
|
||||
pickerItems: signal.NewFunc([]pickerItem{}, nil),
|
||||
pickerFilter: signal.New(""),
|
||||
pickerLoad: signal.New(false),
|
||||
}
|
||||
c.chat = ch
|
||||
ch.syncPerms()
|
||||
ch.load()
|
||||
return ch
|
||||
}
|
||||
@@ -591,24 +597,29 @@ func (ch *chat) applyPick(it pickerItem) {
|
||||
}
|
||||
|
||||
// perms are the pending permission requests for this session.
|
||||
func (ch *chat) perms() signal.Accessor[[]ocapi.PermissionRequest] {
|
||||
return signal.Func(func() []ocapi.PermissionRequest {
|
||||
var out []ocapi.PermissionRequest
|
||||
for _, p := range ch.c.perms.Get() {
|
||||
if p.SessionID == ch.id {
|
||||
out = append(out, p)
|
||||
}
|
||||
func (ch *chat) perms() []ocapi.PermissionRequest {
|
||||
var out []ocapi.PermissionRequest
|
||||
for _, p := range ch.c.perms.Get() {
|
||||
if p.SessionID == ch.id {
|
||||
out = append(out, p)
|
||||
}
|
||||
return out
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// syncPerms publishes this session's pending permission requests. The list
|
||||
// and the flag are plain signals so the section updates without a computed
|
||||
// chain (which is timing-sensitive in the test host).
|
||||
func (ch *chat) syncPerms() {
|
||||
list := ch.perms()
|
||||
ch.permList.Set(list)
|
||||
ch.hasPerms.Set(len(list) > 0)
|
||||
}
|
||||
|
||||
func (ch *chat) permissionSection() ui.Node {
|
||||
list := ch.perms()
|
||||
shown := signal.Func(func() bool { return len(list.Get()) > 0 })
|
||||
return ui.Show(shown, func() ui.Node {
|
||||
return ui.Show(ch.hasPerms, func() ui.Node {
|
||||
return ui.Column(ui.Style{Gap: 6, Padding: ui.Symmetric(6, 12)},
|
||||
ui.For(list, func(p ocapi.PermissionRequest) string { return p.ID },
|
||||
ui.For(ch.permList, func(p ocapi.PermissionRequest) string { return p.ID },
|
||||
func(p signal.Accessor[ocapi.PermissionRequest], _ signal.Accessor[int]) ui.Node {
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Gap: 8, Padding: ui.Symmetric(10, 12),
|
||||
CornerRadius: 12, Background: colors.SecondaryBackground}},
|
||||
@@ -656,6 +667,7 @@ func (ch *chat) reply(req ocapi.PermissionRequest, decision ocapi.PermissionDeci
|
||||
}
|
||||
}
|
||||
ch.c.perms.Set(next)
|
||||
ch.syncPerms()
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -151,8 +151,7 @@ func TestOpenSessionAndSend(t *testing.T) {
|
||||
st := &memStore{}
|
||||
a := uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Tap("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
a.WaitFor("First session")
|
||||
select {
|
||||
case <-srv.ready:
|
||||
@@ -186,8 +185,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
||||
srv := newChatServer(t)
|
||||
// The session list's pending-permission read.
|
||||
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("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
a.WaitFor("First session")
|
||||
select {
|
||||
case <-srv.ready:
|
||||
@@ -199,6 +197,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
||||
a.WaitFor("Hello from the agent")
|
||||
|
||||
srv.push(`{"id":"evt_10","created":200,"type":"permission.asked","data":{"sessionID":"ses_1","id":"per_1","action":"bash","resources":["npm test"]}}`)
|
||||
a.Settle()
|
||||
a.WaitFor("需要权限:bash")
|
||||
a.Expect("npm test")
|
||||
|
||||
@@ -216,8 +215,7 @@ func TestPermissionCardAndReply(t *testing.T) {
|
||||
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("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
a.WaitFor("First session")
|
||||
a.Tap("First session")
|
||||
a.WaitFor("Hello from the agent")
|
||||
@@ -240,8 +238,7 @@ func TestSwitchModel(t *testing.T) {
|
||||
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("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
a.WaitFor("First session")
|
||||
|
||||
a.Tap("新建")
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
package appui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/asuka/colors"
|
||||
"github.com/egoist/asuka/fonts"
|
||||
"github.com/egoist/asuka/signal"
|
||||
"github.com/egoist/asuka/ui"
|
||||
"github.com/openchamber/openchamber-native/internal/storage"
|
||||
)
|
||||
|
||||
// connectionsScreen is the first screen: the saved servers, or the
|
||||
// introduction when there are none. It mirrors the first-party client: the
|
||||
// server last used leads, the others follow, and adding is one tap away.
|
||||
func (c *controller) connectionsScreen() ui.Node {
|
||||
return ui.Dynamic(func() ui.Node {
|
||||
list := c.connections.Get()
|
||||
if len(list) == 0 {
|
||||
return c.firstRun()
|
||||
}
|
||||
lead := list[0]
|
||||
for _, conn := range list {
|
||||
if conn.ID == c.activeID.Get() && c.connected.Get() {
|
||||
lead = conn
|
||||
}
|
||||
}
|
||||
others := make([]storage.Connection, 0, len(list))
|
||||
for _, conn := range list {
|
||||
if conn.ID != lead.ID {
|
||||
others = append(others, conn)
|
||||
}
|
||||
}
|
||||
return ui.Scroll(
|
||||
ui.ScrollProps{
|
||||
Style: ui.Style{Grow: 1},
|
||||
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||
},
|
||||
ui.StaticText("OpenChamber", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold)}),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||
}),
|
||||
c.leadCard(lead),
|
||||
ui.Show(signal.Func(func() bool { return len(c.connections.Get()) > 1 }), func() ui.Node {
|
||||
return ui.Column(ui.Style{Gap: 6},
|
||||
ui.StaticText("其他服务器", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||
ui.For(c.otherConnections(lead.ID), func(conn storage.Connection) string { return conn.ID },
|
||||
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
|
||||
return c.connectionRow(conn)
|
||||
}),
|
||||
)
|
||||
}),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("添加服务器"),
|
||||
Icon: ui.IconPlus,
|
||||
Variant: ui.ButtonTinted,
|
||||
OnPress: c.openAddForm,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) otherConnections(leadID string) signal.Accessor[[]storage.Connection] {
|
||||
return signal.Func(func() []storage.Connection {
|
||||
out := make([]storage.Connection, 0, len(c.connections.Get()))
|
||||
for _, conn := range c.connections.Get() {
|
||||
if conn.ID != leadID {
|
||||
out = append(out, conn)
|
||||
}
|
||||
}
|
||||
return out
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) firstRun() ui.Node {
|
||||
return ui.Scroll(
|
||||
ui.ScrollProps{
|
||||
Style: ui.Style{Grow: 1},
|
||||
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||
},
|
||||
ui.StaticText("OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
|
||||
ui.StaticText("连接到正在运行的 OpenChamber 服务器。保存过的服务器会出现在这里,可以随时切换。",
|
||||
ui.Style{Color: colors.SecondaryLabel}),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||
}),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("手动输入地址"),
|
||||
Icon: "link",
|
||||
Variant: ui.ButtonFilled,
|
||||
OnPress: c.openAddForm,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *controller) leadCard(conn storage.Connection) ui.Node {
|
||||
return ui.View(ui.ViewProps{Style: ui.Style{Padding: ui.All(16), Gap: 8, CornerRadius: 14,
|
||||
Background: colors.SecondaryBackground}},
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
|
||||
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||
),
|
||||
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
|
||||
OnPress: func() { c.connectionActions(conn) }}),
|
||||
),
|
||||
ui.Show(signal.Func(func() bool { return c.activeID.Get() == conn.ID && c.connected.Get() }),
|
||||
func() ui.Node {
|
||||
return ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||
ui.View(ui.ViewProps{Style: ui.Style{Width: ui.Pt(8), Height: ui.Pt(8),
|
||||
CornerRadius: 4, Background: colors.Accent}}),
|
||||
ui.StaticText("已连接", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}),
|
||||
)
|
||||
},
|
||||
func() ui.Node {
|
||||
return ui.Show(signal.Func(func() bool { return c.connecting.Get() == conn.ID }),
|
||||
func() ui.Node {
|
||||
return ui.Row(ui.Style{Gap: 8, Align: ui.AlignCenter},
|
||||
ui.Activity(), ui.StaticText("连接中…", ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel}))
|
||||
},
|
||||
func() ui.Node {
|
||||
return ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("连接"),
|
||||
Variant: ui.ButtonFilled,
|
||||
OnPress: func() { c.connectTo(conn, "", true) },
|
||||
})
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
func (c *controller) connectionRow(conn signal.Accessor[storage.Connection]) ui.Node {
|
||||
return ui.View(ui.ViewProps{
|
||||
OnPress: func() { c.selectConnection(conn.Get()) },
|
||||
Style: ui.Style{Padding: ui.Symmetric(10, 12), CornerRadius: 10, Gap: 6},
|
||||
}, ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 6},
|
||||
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||
ui.Text(signal.Func(func() string { return c.labelOf(conn.Get()) }), ui.Style{Font: fonts.Body, Lines: 1}),
|
||||
ui.Text(signal.Func(func() string { return conn.Get().URL }),
|
||||
ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||
),
|
||||
ui.Button(ui.ButtonProps{Icon: ui.IconMore, Label: ui.Val("操作"),
|
||||
OnPress: func() { c.connectionActions(conn.Get()) }}),
|
||||
))
|
||||
}
|
||||
|
||||
func (c *controller) selectConnection(conn storage.Connection) {
|
||||
c.instancesOpen.Set(false)
|
||||
if conn.ID == c.activeID.Peek() && c.connected.Peek() {
|
||||
return
|
||||
}
|
||||
if c.connected.Peek() {
|
||||
c.logout("")
|
||||
}
|
||||
c.connectTo(conn, "", true)
|
||||
}
|
||||
|
||||
func (c *controller) connectionActions(conn storage.Connection) {
|
||||
ui.Alert(ui.AlertProps{
|
||||
Title: c.labelOf(conn),
|
||||
ActionSheet: true,
|
||||
Actions: []ui.Action{
|
||||
{Title: ui.Val("连接"), Icon: "play", OnPress: func() { c.selectConnection(conn) }},
|
||||
{Title: ui.Val("编辑"), Icon: "pencil", OnPress: func() { c.openEditForm(conn) }},
|
||||
{Title: ui.Val("删除"), Icon: ui.IconTrash, Role: ui.ActionDestructive,
|
||||
OnPress: func() { c.confirmDeleteConnection(conn) }},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) confirmDeleteConnection(conn storage.Connection) {
|
||||
ui.Alert(ui.AlertProps{
|
||||
Title: "删除服务器?",
|
||||
Message: "只会删除这个客户端里保存的连接,服务器上的数据不受影响。",
|
||||
Actions: []ui.Action{
|
||||
{Title: ui.Val("取消"), Role: ui.ActionCancel},
|
||||
{Title: ui.Val("删除"), Role: ui.ActionDestructive,
|
||||
OnPress: func() { c.deleteConnection(conn) }},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) deleteConnection(conn storage.Connection) {
|
||||
if c.activeID.Peek() == conn.ID {
|
||||
c.logout("")
|
||||
}
|
||||
list := c.connections.Peek()
|
||||
next := make([]storage.Connection, 0, len(list))
|
||||
for _, saved := range list {
|
||||
if saved.ID != conn.ID {
|
||||
next = append(next, saved)
|
||||
}
|
||||
}
|
||||
c.st.SaveConnections(next)
|
||||
c.connections.Set(next)
|
||||
go func() { _ = c.st.ClearToken(conn) }()
|
||||
}
|
||||
|
||||
// formSheet is the add/edit form, a full-screen sheet like the first-party
|
||||
// client's panel.
|
||||
func (c *controller) formSheet() ui.Node {
|
||||
title := "添加服务器"
|
||||
if c.formEditID != "" {
|
||||
title = "编辑服务器"
|
||||
}
|
||||
submit := "连接"
|
||||
if c.connected.Peek() {
|
||||
submit = "保存"
|
||||
}
|
||||
return ui.Sheet(ui.SheetProps{
|
||||
Open: c.formOpen,
|
||||
FullScreen: true,
|
||||
Content: func() ui.Node {
|
||||
return ui.SafeArea(ui.Style{Grow: 1},
|
||||
ui.Scroll(
|
||||
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14}},
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter},
|
||||
ui.StaticText(title, ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.closeForm}),
|
||||
),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.formLabel,
|
||||
Placeholder: ui.Val("名称(可选)"),
|
||||
}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.url,
|
||||
Placeholder: ui.Val("http://192.168.1.5:3000"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
ContentType: "url",
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
ReturnKey: ui.ReturnNext,
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("使用代理", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.formUseProxy}),
|
||||
),
|
||||
ui.Show(c.formUseProxy, func() ui.Node {
|
||||
return ui.TextField(ui.TextFieldProps{
|
||||
Value: c.formProxy,
|
||||
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
})
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.formInsecure}),
|
||||
),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||
}),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val(submit),
|
||||
Variant: ui.ButtonFilled,
|
||||
Disabled: signal.Func(func() bool { return c.connecting.Get() != "" }),
|
||||
OnPress: c.submitForm,
|
||||
}),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) passwordSheet() ui.Node {
|
||||
return ui.Sheet(ui.SheetProps{
|
||||
Open: c.passwordOpen,
|
||||
Detents: ui.DetentMedium,
|
||||
Grabber: true,
|
||||
OnDismiss: c.cancelPassword,
|
||||
Content: func() ui.Node {
|
||||
conn := c.passwordFor
|
||||
for _, saved := range c.connections.Peek() {
|
||||
if saved.ID == conn.ID {
|
||||
conn = saved
|
||||
}
|
||||
}
|
||||
return ui.SafeArea(ui.Style{Padding: ui.All(20), Gap: 14},
|
||||
ui.StaticText(c.labelOf(conn), ui.Style{Font: fonts.Headline, Lines: 1}),
|
||||
ui.StaticText(conn.URL, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||
ui.StaticText("这台服务器需要密码。", ui.Style{Color: colors.SecondaryLabel}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.passwordText,
|
||||
Placeholder: ui.Val("密码"),
|
||||
Secure: true,
|
||||
ContentType: ui.ContentPassword,
|
||||
ReturnKey: ui.ReturnGo,
|
||||
OnSubmit: c.submitPassword,
|
||||
}),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||
}),
|
||||
ui.Row(ui.Style{Justify: ui.JustifyEnd, Gap: 8},
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("取消"), OnPress: c.cancelPassword}),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("解锁"),
|
||||
Variant: ui.ButtonFilled,
|
||||
Disabled: signal.Func(func() bool {
|
||||
return c.passwordBusy.Get() || strings.TrimSpace(c.passwordText.Get()) == ""
|
||||
}),
|
||||
OnPress: c.submitPassword,
|
||||
}),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// instancesSheet is the switcher while connected: the same list, in a sheet.
|
||||
func (c *controller) instancesSheet() ui.Node {
|
||||
return ui.Sheet(ui.SheetProps{
|
||||
Open: c.instancesOpen,
|
||||
FullScreen: true,
|
||||
Content: func() ui.Node {
|
||||
return ui.SafeArea(ui.Style{Grow: 1},
|
||||
ui.Scroll(
|
||||
ui.ScrollProps{Style: ui.Style{Grow: 1}, ContentStyle: ui.Style{Padding: ui.All(20), Gap: 12}},
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter},
|
||||
ui.StaticText("实例", ui.Style{Font: fonts.Title2.Weighted(fonts.Bold), Grow: 1}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("关闭"),
|
||||
OnPress: func() { c.instancesOpen.Set(false) }}),
|
||||
),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red})
|
||||
}),
|
||||
ui.For(c.connections, func(conn storage.Connection) string { return conn.ID },
|
||||
func(conn signal.Accessor[storage.Connection], _ signal.Accessor[int]) ui.Node {
|
||||
return ui.Column(ui.Style{Gap: 4},
|
||||
c.connectionRow(conn),
|
||||
ui.Show(signal.Func(func() bool {
|
||||
return conn.Get().ID == c.activeID.Get() && c.connected.Get()
|
||||
}), func() ui.Node {
|
||||
return ui.StaticText("当前连接", ui.Style{Font: fonts.Footnote,
|
||||
Color: colors.SecondaryLabel, Padding: ui.Symmetric(0, 12)})
|
||||
}),
|
||||
)
|
||||
}),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("添加服务器"),
|
||||
Icon: ui.IconPlus,
|
||||
Variant: ui.ButtonTinted,
|
||||
OnPress: func() {
|
||||
c.instancesOpen.Set(false)
|
||||
c.openAddForm()
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -79,7 +79,7 @@ type permissionData struct {
|
||||
|
||||
// startEvents subscribes to the server's event stream for the given client.
|
||||
// It must run on the main thread (it writes the cancel function).
|
||||
func (c *controller) startEvents(client *ocapi.Client, p connectParams) {
|
||||
func (c *controller) startEvents(client *ocapi.Client) {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
}
|
||||
@@ -226,6 +226,9 @@ func (c *controller) applyEvent(ev ocapi.Event) {
|
||||
ID: d.ID, SessionID: d.SessionID, Action: d.Action, Resources: d.Resources,
|
||||
})
|
||||
c.perms.Set(next)
|
||||
if c.chat != nil {
|
||||
c.chat.syncPerms()
|
||||
}
|
||||
|
||||
case "permission.replied":
|
||||
var d struct {
|
||||
@@ -243,6 +246,9 @@ func (c *controller) applyEvent(ev ocapi.Event) {
|
||||
}
|
||||
if len(next) != len(list) {
|
||||
c.perms.Set(next)
|
||||
if c.chat != nil {
|
||||
c.chat.syncPerms()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+297
-136
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -50,20 +51,34 @@ func newApp(st storage.Store) (*controller, ui.Node) {
|
||||
type controller struct {
|
||||
st storage.Store
|
||||
|
||||
connections *signal.Signal[[]storage.Connection]
|
||||
|
||||
url *signal.Signal[string]
|
||||
password *signal.Signal[string]
|
||||
useProxy *signal.Signal[bool]
|
||||
proxy *signal.Signal[string]
|
||||
insecure *signal.Signal[bool]
|
||||
status *signal.Signal[string]
|
||||
errorMsg *signal.Signal[string]
|
||||
|
||||
server *signal.Signal[string]
|
||||
connected *signal.Signal[bool]
|
||||
busy *signal.Signal[bool]
|
||||
sessions *signal.Signal[[]ocapi.Session]
|
||||
active *signal.Signal[map[string]bool]
|
||||
perms *signal.Signal[[]ocapi.PermissionRequest]
|
||||
formOpen *signal.Signal[bool]
|
||||
formEditID string
|
||||
formLabel *signal.Signal[string]
|
||||
formUseProxy *signal.Signal[bool]
|
||||
formProxy *signal.Signal[string]
|
||||
formInsecure *signal.Signal[bool]
|
||||
|
||||
passwordOpen *signal.Signal[bool]
|
||||
passwordFor storage.Connection
|
||||
passwordText *signal.Signal[string]
|
||||
passwordBusy *signal.Signal[bool]
|
||||
|
||||
instancesOpen *signal.Signal[bool]
|
||||
|
||||
server *signal.Signal[string]
|
||||
connected *signal.Signal[bool]
|
||||
busy *signal.Signal[bool]
|
||||
connecting *signal.Signal[string]
|
||||
activeID *signal.Signal[string]
|
||||
sessions *signal.Signal[[]ocapi.Session]
|
||||
active *signal.Signal[map[string]bool]
|
||||
perms *signal.Signal[[]ocapi.PermissionRequest]
|
||||
defaultDir *signal.Signal[string]
|
||||
|
||||
newOpen *signal.Signal[bool]
|
||||
@@ -78,45 +93,54 @@ type controller struct {
|
||||
}
|
||||
|
||||
func newController(st storage.Store) *controller {
|
||||
conns := st.Connections()
|
||||
sort.SliceStable(conns, func(i, j int) bool { return conns[i].LastUsedAt > conns[j].LastUsedAt })
|
||||
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),
|
||||
defaultDir: signal.New(""),
|
||||
newOpen: signal.New(false),
|
||||
newTitle: signal.New(""),
|
||||
newDir: signal.New(0),
|
||||
creating: signal.New(false),
|
||||
st: st,
|
||||
connections: signal.NewFunc(conns, nil),
|
||||
url: signal.New(""),
|
||||
status: signal.New(""),
|
||||
errorMsg: signal.New(""),
|
||||
formOpen: signal.New(false),
|
||||
formLabel: signal.New(""),
|
||||
formUseProxy: signal.New(false),
|
||||
formProxy: signal.New(""),
|
||||
formInsecure: signal.New(false),
|
||||
passwordOpen: signal.New(false),
|
||||
passwordText: signal.New(""),
|
||||
passwordBusy: signal.New(false),
|
||||
instancesOpen: signal.New(false),
|
||||
server: signal.New(""),
|
||||
connected: signal.New(false),
|
||||
busy: signal.New(false),
|
||||
connecting: signal.New(""),
|
||||
activeID: signal.New(""),
|
||||
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)
|
||||
c.proxy.Set(conn.Proxy)
|
||||
c.useProxy.Set(conn.Proxy != "")
|
||||
c.insecure.Set(conn.Insecure)
|
||||
c.status.Set("正在恢复连接…")
|
||||
c.reconnect(conn)
|
||||
// Come back to the server last used, as the first-party client does.
|
||||
if len(conns) > 0 {
|
||||
c.connectTo(conns[0], "", false)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *controller) screen() ui.Node {
|
||||
return ui.SafeArea(ui.Style{Grow: 1},
|
||||
ui.Show(c.connected, c.sessionsScreen, c.connectScreen),
|
||||
ui.Show(c.connected, c.sessionsScreen, c.connectionsScreen),
|
||||
c.formSheet(),
|
||||
c.passwordSheet(),
|
||||
c.instancesSheet(),
|
||||
c.newSessionSheetNode(),
|
||||
)
|
||||
}
|
||||
|
||||
// shutdown stops what the controller started; the root owner calls it when
|
||||
// the app (or a test) unmounts.
|
||||
func (c *controller) shutdown() {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
@@ -125,75 +149,42 @@ func (c *controller) shutdown() {
|
||||
c.client = nil
|
||||
}
|
||||
|
||||
func (c *controller) connect() {
|
||||
if c.busy.Peek() {
|
||||
// connectTo starts a connection attempt off the main thread. password is
|
||||
// the one the user typed, if any; explicit marks a tap (a password may be
|
||||
// asked for), while the launch reconnect stays quiet.
|
||||
func (c *controller) connectTo(conn storage.Connection, password string, explicit bool) {
|
||||
if c.connecting.Peek() != "" {
|
||||
return
|
||||
}
|
||||
params := connectParams{
|
||||
url: strings.TrimSpace(c.url.Peek()),
|
||||
password: c.password.Peek(),
|
||||
insecure: c.insecure.Peek(),
|
||||
explicit: true,
|
||||
}
|
||||
if c.useProxy.Peek() {
|
||||
params.proxy = strings.TrimSpace(c.proxy.Peek())
|
||||
}
|
||||
c.busy.Set(true)
|
||||
c.status.Set("连接中…")
|
||||
c.connecting.Set(conn.ID)
|
||||
c.errorMsg.Set("")
|
||||
go func() {
|
||||
c.establish(params, "")
|
||||
c.establish(conn, password, explicit)
|
||||
}()
|
||||
}
|
||||
|
||||
// reconnect retries a stored connection, whose token lives in secure
|
||||
// storage (readable only off the main thread).
|
||||
func (c *controller) reconnect(conn storage.Connection) {
|
||||
params := connectParams{
|
||||
url: conn.URL,
|
||||
proxy: conn.Proxy,
|
||||
insecure: conn.Insecure,
|
||||
}
|
||||
if conn.Passwordless {
|
||||
// No token was issued; the server answers without one.
|
||||
go func() { c.establish(params, "") }()
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
token, ok, err := c.st.LoadToken(conn.URL)
|
||||
if err != nil || !ok {
|
||||
ui.Post(func() { c.status.Set("请重新输入密码") })
|
||||
return
|
||||
}
|
||||
c.establish(params, token)
|
||||
}()
|
||||
}
|
||||
|
||||
type connectParams struct {
|
||||
url string
|
||||
password string
|
||||
proxy string
|
||||
insecure bool
|
||||
// explicit means the user pressed Connect: a password prompt is
|
||||
// theirs to answer. A background reconnect never asks.
|
||||
explicit bool
|
||||
}
|
||||
|
||||
// establish runs the whole connect sequence off the main thread: health,
|
||||
// token probe, optional password login, first page of sessions. It reports
|
||||
// through the signals with ui.Post.
|
||||
func (c *controller) establish(p connectParams, token string) {
|
||||
// establish runs the whole connect sequence: health, token probe, optional
|
||||
// password login, first page of sessions.
|
||||
func (c *controller) establish(conn storage.Connection, password string, explicit bool) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
defer cancel()
|
||||
|
||||
fail := func(err error) {
|
||||
ui.Post(func() {
|
||||
c.busy.Set(false)
|
||||
c.status.Set(friendlyError(err))
|
||||
c.connecting.Set("")
|
||||
c.errorMsg.Set(friendlyError(err))
|
||||
})
|
||||
}
|
||||
if !strings.Contains(conn.URL, "://") {
|
||||
normalized, err := ocapi.NormalizeBaseURL(conn.URL)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
conn.URL = normalized
|
||||
}
|
||||
|
||||
opts := ocapi.Options{Proxy: p.proxy, InsecureSkipVerify: p.insecure}
|
||||
client, err := ocapi.New(p.url, opts)
|
||||
client, err := ocapi.New(conn.URL, ocapi.Options{Proxy: conn.Proxy, InsecureSkipVerify: conn.Insecure})
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
@@ -208,48 +199,59 @@ func (c *controller) establish(p connectParams, token string) {
|
||||
return
|
||||
}
|
||||
|
||||
passwordless := false
|
||||
if token != "" {
|
||||
client.SetToken(token)
|
||||
token := ""
|
||||
if !conn.Passwordless {
|
||||
if t, ok, err := c.st.LoadToken(conn); err == nil && ok {
|
||||
token = t
|
||||
client.SetToken(t)
|
||||
}
|
||||
}
|
||||
passwordless := conn.Passwordless
|
||||
auth, authErr := client.SessionStatus(ctx)
|
||||
switch {
|
||||
case authErr == nil:
|
||||
passwordless = auth.Disabled
|
||||
case ocapi.IsUnauthorized(authErr):
|
||||
if strings.TrimSpace(p.password) == "" {
|
||||
if token != "" {
|
||||
// The stored token is no good: drop it so the next
|
||||
// attempt does not retry with it.
|
||||
server := client.BaseURL()
|
||||
go func() { _ = c.st.ClearToken(server) }()
|
||||
}
|
||||
if p.explicit {
|
||||
fail(errUnauthorized)
|
||||
if strings.TrimSpace(password) == "" {
|
||||
if explicit {
|
||||
ui.Post(func() {
|
||||
c.connecting.Set("")
|
||||
c.askPassword(conn)
|
||||
})
|
||||
} else {
|
||||
ui.Post(func() { c.status.Set("登录已失效,请输入密码重新连接") })
|
||||
ui.Post(func() {
|
||||
c.connecting.Set("")
|
||||
c.errorMsg.Set("登录已失效,请重新输入密码")
|
||||
c.askPassword(conn)
|
||||
})
|
||||
}
|
||||
if token != "" {
|
||||
go func() { _ = c.st.ClearToken(conn) }()
|
||||
}
|
||||
return
|
||||
}
|
||||
res, err := client.Login(ctx, ocapi.LoginRequest{
|
||||
Password: p.password,
|
||||
Password: password,
|
||||
DedupeKey: c.st.InstallID(),
|
||||
ClientLabel: "OpenChamber Native",
|
||||
ClientKind: "mobile",
|
||||
DevicePlatform: "android",
|
||||
})
|
||||
if err != nil {
|
||||
fail(err)
|
||||
ui.Post(func() {
|
||||
c.connecting.Set("")
|
||||
c.errorMsg.Set(friendlyError(err))
|
||||
c.passwordBusy.Set(false)
|
||||
c.passwordOpen.Set(true)
|
||||
})
|
||||
return
|
||||
}
|
||||
if res.ClientToken == "" {
|
||||
fail(errors.New("登录没有返回设备 token"))
|
||||
return
|
||||
}
|
||||
if err := c.st.SaveToken(client.BaseURL(), res.ClientToken); err != nil {
|
||||
// A token that cannot be persisted still works for this run.
|
||||
_ = err
|
||||
}
|
||||
_ = c.st.SaveToken(conn.ID, res.ClientToken)
|
||||
passwordless = false
|
||||
default:
|
||||
fail(authErr)
|
||||
return
|
||||
@@ -270,19 +272,23 @@ func (c *controller) establish(p connectParams, token string) {
|
||||
}
|
||||
perms, _ := client.PendingPermissions(ctx, "")
|
||||
|
||||
info := fmt.Sprintf("%s · OpenChamber %s", client.BaseURL(), health.OpenChamberVersion)
|
||||
info := fmt.Sprintf("%s · OpenChamber %s", c.labelOf(conn), health.OpenChamberVersion)
|
||||
if !health.IsOpenCodeReady {
|
||||
info += " · OpenCode 未就绪"
|
||||
}
|
||||
c.st.SaveConnection(storage.Connection{
|
||||
URL: client.BaseURL(),
|
||||
Proxy: p.proxy,
|
||||
Insecure: p.insecure,
|
||||
ServerID: health.ServerID,
|
||||
Passwordless: passwordless,
|
||||
})
|
||||
|
||||
conn.URL = client.BaseURL()
|
||||
if conn.Label == "" {
|
||||
conn.Label = hostOf(conn.URL)
|
||||
}
|
||||
conn.ServerID = health.ServerID
|
||||
conn.Passwordless = passwordless
|
||||
conn.LastUsedAt = time.Now().UnixMilli()
|
||||
|
||||
ui.Post(func() {
|
||||
c.connecting.Set("")
|
||||
c.saveConnection(conn)
|
||||
c.activeID.Set(conn.ID)
|
||||
c.client = client
|
||||
c.sessions.Set(page.Data)
|
||||
c.active.Set(running)
|
||||
@@ -290,12 +296,47 @@ func (c *controller) establish(p connectParams, token string) {
|
||||
c.server.Set(info)
|
||||
c.connected.Set(true)
|
||||
c.busy.Set(false)
|
||||
c.password.Set("")
|
||||
c.formOpen.Set(false)
|
||||
c.passwordOpen.Set(false)
|
||||
c.passwordText.Set("")
|
||||
c.passwordBusy.Set(false)
|
||||
c.instancesOpen.Set(false)
|
||||
c.errorMsg.Set("")
|
||||
c.status.Set(fmt.Sprintf("已连接,%d 个会话", len(page.Data)))
|
||||
c.startEvents(client, p)
|
||||
c.startEvents(client)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *controller) saveConnection(conn storage.Connection) {
|
||||
conns := c.connections.Peek()
|
||||
found := false
|
||||
next := make([]storage.Connection, 0, len(conns)+1)
|
||||
for _, existing := range conns {
|
||||
if existing.ID == conn.ID {
|
||||
next = append(next, conn)
|
||||
found = true
|
||||
} else {
|
||||
next = append(next, existing)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if conn.ID == "" {
|
||||
conn.ID = storage.NewID()
|
||||
}
|
||||
next = append(next, conn)
|
||||
}
|
||||
sort.SliceStable(next, func(i, j int) bool { return next[i].LastUsedAt > next[j].LastUsedAt })
|
||||
c.st.SaveConnections(next)
|
||||
c.connections.Set(next)
|
||||
}
|
||||
|
||||
func (c *controller) labelOf(conn storage.Connection) string {
|
||||
if strings.TrimSpace(conn.Label) != "" {
|
||||
return conn.Label
|
||||
}
|
||||
return hostOf(conn.URL)
|
||||
}
|
||||
|
||||
func (c *controller) refresh() {
|
||||
if c.client == nil || c.busy.Peek() {
|
||||
return
|
||||
@@ -305,9 +346,6 @@ 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))
|
||||
@@ -322,7 +360,7 @@ func (c *controller) refresh() {
|
||||
c.logout("登录已失效,请输入密码重新连接")
|
||||
return
|
||||
}
|
||||
c.status.Set(friendlyError(err))
|
||||
c.errorMsg.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
c.sessions.Set(page.Data)
|
||||
@@ -337,31 +375,143 @@ func (c *controller) refresh() {
|
||||
}()
|
||||
}
|
||||
|
||||
// logout drops the session but keeps the address so the user only types
|
||||
// the password again.
|
||||
// logout drops the live session but keeps the saved servers.
|
||||
func (c *controller) logout(reason string) {
|
||||
if c.cancelSSE != nil {
|
||||
c.cancelSSE()
|
||||
c.cancelSSE = nil
|
||||
}
|
||||
if c.client != nil {
|
||||
server := c.client.BaseURL()
|
||||
go func() { _ = c.st.ClearToken(server) }()
|
||||
}
|
||||
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
||||
c.chat.nav.Pop()
|
||||
var conn storage.Connection
|
||||
if id := c.activeID.Peek(); id != "" {
|
||||
for _, saved := range c.connections.Peek() {
|
||||
if saved.ID == id {
|
||||
conn = saved
|
||||
}
|
||||
}
|
||||
}
|
||||
c.client = nil
|
||||
c.connected.Set(false)
|
||||
c.activeID.Set("")
|
||||
c.sessions.Set(nil)
|
||||
c.active.Set(map[string]bool{})
|
||||
c.perms.Set(nil)
|
||||
c.server.Set("")
|
||||
c.status.Set(reason)
|
||||
c.errorMsg.Set(reason)
|
||||
if conn.ID != "" && reason != "" {
|
||||
go func() { _ = c.st.ClearToken(conn) }()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *controller) disconnect() {
|
||||
c.logout("已断开")
|
||||
if c.chat != nil && c.chat.nav != nil && c.chat.nav.Depth() > 1 {
|
||||
c.chat.nav.Pop()
|
||||
}
|
||||
c.logout("")
|
||||
}
|
||||
|
||||
// --- form ---------------------------------------------------------------
|
||||
|
||||
func (c *controller) openAddForm() {
|
||||
c.formEditID = ""
|
||||
c.url.Set("")
|
||||
c.formLabel.Set("")
|
||||
c.formUseProxy.Set(false)
|
||||
c.formProxy.Set("")
|
||||
c.formInsecure.Set(false)
|
||||
c.errorMsg.Set("")
|
||||
c.formOpen.Set(true)
|
||||
}
|
||||
|
||||
func (c *controller) openEditForm(conn storage.Connection) {
|
||||
c.formEditID = conn.ID
|
||||
c.url.Set(conn.URL)
|
||||
c.formLabel.Set(conn.Label)
|
||||
c.formUseProxy.Set(conn.Proxy != "")
|
||||
c.formProxy.Set(conn.Proxy)
|
||||
c.formInsecure.Set(conn.Insecure)
|
||||
c.errorMsg.Set("")
|
||||
c.formOpen.Set(true)
|
||||
}
|
||||
|
||||
func (c *controller) closeForm() {
|
||||
c.formOpen.Set(false)
|
||||
c.errorMsg.Set("")
|
||||
}
|
||||
|
||||
func (c *controller) submitForm() {
|
||||
raw := strings.TrimSpace(c.url.Peek())
|
||||
if raw == "" {
|
||||
c.errorMsg.Set("请输入服务器地址")
|
||||
return
|
||||
}
|
||||
normalized, err := ocapi.NormalizeBaseURL(raw)
|
||||
if err != nil {
|
||||
c.errorMsg.Set(friendlyError(err))
|
||||
return
|
||||
}
|
||||
conn := storage.Connection{ID: c.formEditID, URL: normalized, Label: strings.TrimSpace(c.formLabel.Peek())}
|
||||
if c.formUseProxy.Peek() {
|
||||
conn.Proxy = strings.TrimSpace(c.formProxy.Peek())
|
||||
}
|
||||
conn.Insecure = c.formInsecure.Peek()
|
||||
if conn.ID != "" {
|
||||
for _, saved := range c.connections.Peek() {
|
||||
if saved.ID == conn.ID {
|
||||
conn.ServerID = saved.ServerID
|
||||
conn.Passwordless = saved.Passwordless
|
||||
conn.LastUsedAt = saved.LastUsedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
if conn.ID == "" {
|
||||
conn.ID = storage.NewID()
|
||||
}
|
||||
c.saveConnection(conn)
|
||||
c.formOpen.Set(false)
|
||||
|
||||
if !c.connected.Peek() {
|
||||
c.connectTo(conn, "", true)
|
||||
return
|
||||
}
|
||||
c.status.Set("已保存")
|
||||
}
|
||||
|
||||
// --- password -----------------------------------------------------------
|
||||
|
||||
func (c *controller) askPassword(conn storage.Connection) {
|
||||
c.passwordFor = conn
|
||||
c.passwordText.Set("")
|
||||
c.passwordBusy.Set(false)
|
||||
c.passwordOpen.Set(true)
|
||||
}
|
||||
|
||||
func (c *controller) submitPassword() {
|
||||
if c.passwordBusy.Peek() {
|
||||
return
|
||||
}
|
||||
pw := c.passwordText.Peek()
|
||||
if strings.TrimSpace(pw) == "" {
|
||||
return
|
||||
}
|
||||
conn := c.passwordFor
|
||||
c.passwordBusy.Set(true)
|
||||
c.passwordOpen.Set(false)
|
||||
c.connectToPassword(conn, pw)
|
||||
}
|
||||
|
||||
func (c *controller) connectToPassword(conn storage.Connection, password string) {
|
||||
if c.connecting.Peek() != "" {
|
||||
return
|
||||
}
|
||||
c.connecting.Set(conn.ID)
|
||||
c.errorMsg.Set("")
|
||||
go func() { c.establish(conn, password, true) }()
|
||||
}
|
||||
|
||||
func (c *controller) cancelPassword() {
|
||||
c.passwordOpen.Set(false)
|
||||
c.passwordText.Set("")
|
||||
c.passwordBusy.Set(false)
|
||||
}
|
||||
|
||||
var errUnauthorized = errors.New("这个服务器需要密码")
|
||||
@@ -399,6 +549,17 @@ func friendlyError(err error) string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func hostOf(raw string) string {
|
||||
s := strings.TrimSpace(raw)
|
||||
if i := strings.Index(s, "://"); i >= 0 {
|
||||
s = s[i+3:]
|
||||
}
|
||||
if i := strings.IndexByte(s, '/'); i >= 0 {
|
||||
s = s[:i]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func shortPath(p string) string {
|
||||
p = strings.TrimRight(p, "/")
|
||||
if p == "" {
|
||||
|
||||
+150
-80
@@ -16,71 +16,77 @@ import (
|
||||
// memStore is a storage.Store that keeps everything in memory.
|
||||
type memStore struct {
|
||||
mu sync.Mutex
|
||||
conn storage.Connection
|
||||
has bool
|
||||
conns []storage.Connection
|
||||
tokens map[string]string
|
||||
id string
|
||||
}
|
||||
|
||||
func (m *memStore) Connection() (storage.Connection, bool) {
|
||||
func (m *memStore) Connections() []storage.Connection {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.conn, m.has
|
||||
out := make([]storage.Connection, len(m.conns))
|
||||
copy(out, m.conns)
|
||||
return out
|
||||
}
|
||||
func (m *memStore) SaveConnection(c storage.Connection) {
|
||||
|
||||
func (m *memStore) SaveConnections(list []storage.Connection) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.conn, m.has = c, c.URL != ""
|
||||
}
|
||||
func (m *memStore) ClearConnection() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.conn, m.has = storage.Connection{}, false
|
||||
out := make([]storage.Connection, len(list))
|
||||
copy(out, list)
|
||||
m.conns = out
|
||||
}
|
||||
|
||||
func (m *memStore) InstallID() string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.id == "" {
|
||||
m.id = "test-install"
|
||||
}
|
||||
return m.id
|
||||
}
|
||||
func (m *memStore) LoadToken(server string) (string, bool, error) {
|
||||
|
||||
func (m *memStore) LoadToken(c storage.Connection) (string, bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
t, ok := m.tokens[server]
|
||||
t, ok := m.tokens[c.ID]
|
||||
return t, ok, nil
|
||||
}
|
||||
func (m *memStore) SaveToken(server, token string) error {
|
||||
|
||||
func (m *memStore) SaveToken(id, token string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.tokens == nil {
|
||||
m.tokens = map[string]string{}
|
||||
}
|
||||
m.tokens[server] = token
|
||||
return nil
|
||||
}
|
||||
func (m *memStore) ClearToken(server string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.tokens, server)
|
||||
m.tokens[id] = token
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) token(server string) string {
|
||||
func (m *memStore) ClearToken(c storage.Connection) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.tokens[server]
|
||||
delete(m.tokens, c.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memStore) connection() storage.Connection {
|
||||
func (m *memStore) token(id string) string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.conn
|
||||
return m.tokens[id]
|
||||
}
|
||||
|
||||
func (m *memStore) connections() []storage.Connection {
|
||||
return m.Connections()
|
||||
}
|
||||
|
||||
// fakeServer stands in for OpenChamber: /health, /auth/session and the
|
||||
// session list. password "" with validToken "" makes it passwordless.
|
||||
func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
|
||||
// session list. An empty password makes it passwordless.
|
||||
func fakeServer(t *testing.T, password, validToken, sessionTitle string) *httptest.Server {
|
||||
t.Helper()
|
||||
if sessionTitle == "" {
|
||||
sessionTitle = "First session"
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
authorized := func(r *http.Request) bool {
|
||||
if validToken == "" {
|
||||
@@ -117,15 +123,16 @@ func fakeServer(t *testing.T, password, validToken string) *httptest.Server {
|
||||
fmt.Fprintf(w, `{"authenticated":true,"clientToken":%q}`, validToken)
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("/api/location", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"directory":"/home/me/project","project":{"id":"p1"}}`)
|
||||
})
|
||||
mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !authorized(r) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
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":{}}`)
|
||||
fmt.Fprintf(w, `{"data":[{"id":"ses_1","title":%q,"time":{"created":1,"updated":2},
|
||||
"location":{"directory":"/home/me/project"},"model":{"id":"m","providerID":"p"}}],"cursor":{}}`, sessionTitle)
|
||||
})
|
||||
mux.HandleFunc("/api/session/active", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"data":{"ses_1":{"type":"running"}}}`)
|
||||
@@ -151,86 +158,149 @@ func mount(t *testing.T, st *memStore) *uitest.App {
|
||||
return uitest.Mount(t, func() ui.Node { return rootWithStore(st) }, uitest.Platform(ui.PlatformAndroid))
|
||||
}
|
||||
|
||||
func TestConnectWithPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
// connectViaForm adds a server from the first screen (or the saved list)
|
||||
// and taps Connect.
|
||||
func connectViaForm(t *testing.T, a *uitest.App, url string) {
|
||||
t.Helper()
|
||||
if a.Has("手动输入地址") {
|
||||
a.Tap("手动输入地址")
|
||||
} else {
|
||||
a.Tap("添加服务器")
|
||||
}
|
||||
a.Type("http://192.168.1.5:3000", url)
|
||||
a.Tap("连接")
|
||||
}
|
||||
|
||||
func unlockWith(t *testing.T, a *uitest.App, password string) {
|
||||
t.Helper()
|
||||
a.WaitFor("这台服务器需要密码。")
|
||||
a.Type("密码", password)
|
||||
a.Tap("解锁")
|
||||
}
|
||||
|
||||
func TestConnectWithPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||
st := &memStore{}
|
||||
a := mount(t, st)
|
||||
a.Expect("连接到 OpenChamber")
|
||||
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Type("密码(可选)", "secret")
|
||||
a.Tap("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
unlockWith(t, a, "secret")
|
||||
a.WaitFor("First session")
|
||||
a.ExpectNo("密码(可选)")
|
||||
|
||||
if got := st.connection().URL; got != srv.URL {
|
||||
t.Errorf("connection not saved: %q", got)
|
||||
conns := st.connections()
|
||||
if len(conns) != 1 || conns[0].URL != srv.URL {
|
||||
t.Fatalf("connections = %+v", conns)
|
||||
}
|
||||
if got := st.token(srv.URL); got != "oc_client_test" {
|
||||
t.Errorf("token not saved: %q", got)
|
||||
if got := st.token(conns[0].ID); got != "oc_client_test" {
|
||||
t.Errorf("token = %q", got)
|
||||
}
|
||||
if conns[0].Passwordless {
|
||||
t.Error("password server marked passwordless")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrongPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
a := mount(t, &memStore{})
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Type("密码(可选)", "nope")
|
||||
a.Tap("连接")
|
||||
func TestWrongPasswordThenRetry(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||
st := &memStore{}
|
||||
a := mount(t, st)
|
||||
connectViaForm(t, a, srv.URL)
|
||||
unlockWith(t, a, "nope")
|
||||
a.WaitFor("密码错误")
|
||||
// The prompt stays up so the password can be retried.
|
||||
a.Type("密码", "secret")
|
||||
a.Tap("解锁")
|
||||
a.WaitFor("First session")
|
||||
}
|
||||
|
||||
func TestAutoReconnectWithStoredToken(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||
st := &memStore{
|
||||
conn: storage.Connection{URL: srv.URL},
|
||||
has: true,
|
||||
tokens: map[string]string{srv.URL: "oc_client_test"},
|
||||
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
|
||||
tokens: map[string]string{"a": "oc_client_test"},
|
||||
}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("First session")
|
||||
a.ExpectNo("连接到 OpenChamber")
|
||||
a.ExpectNo("手动输入地址")
|
||||
a.ExpectNo("这台服务器需要密码。")
|
||||
}
|
||||
|
||||
func TestExpiredTokenAsksForPassword(t *testing.T) {
|
||||
srv := fakeServer(t, "secret", "oc_client_test")
|
||||
|
||||
srv := fakeServer(t, "secret", "oc_client_test", "")
|
||||
st := &memStore{
|
||||
conn: storage.Connection{URL: srv.URL},
|
||||
has: true,
|
||||
tokens: map[string]string{srv.URL: "revoked"},
|
||||
conns: []storage.Connection{{ID: "a", URL: srv.URL, Label: "Home", LastUsedAt: 1}},
|
||||
tokens: map[string]string{"a": "revoked"},
|
||||
}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("登录已失效,请输入密码重新连接")
|
||||
a.Expect("连接到 OpenChamber")
|
||||
a.Until("the revoked token to be dropped", func() bool { return st.token(srv.URL) == "" })
|
||||
a.WaitFor("登录已失效,请重新输入密码")
|
||||
a.Until("the revoked token to be dropped", func() bool { return st.token("a") == "" })
|
||||
unlockWith(t, a, "secret")
|
||||
a.WaitFor("First session")
|
||||
}
|
||||
|
||||
func TestPasswordlessServer(t *testing.T) {
|
||||
srv := fakeServer(t, "", "")
|
||||
|
||||
srv := fakeServer(t, "", "", "")
|
||||
st := &memStore{}
|
||||
a := mount(t, st)
|
||||
a.Type("http://192.168.1.5:3000", srv.URL)
|
||||
a.Tap("连接")
|
||||
connectViaForm(t, a, srv.URL)
|
||||
a.WaitFor("First session")
|
||||
if got := st.connection(); !got.Passwordless {
|
||||
t.Errorf("passwordless not remembered: %+v", got)
|
||||
conns := st.connections()
|
||||
if len(conns) != 1 || !conns[0].Passwordless {
|
||||
t.Fatalf("connections = %+v", conns)
|
||||
}
|
||||
if got := st.token(conns[0].ID); got != "" {
|
||||
t.Errorf("unexpected token %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoReconnectPasswordlessWithoutToken(t *testing.T) {
|
||||
srv := fakeServer(t, "", "")
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
st := &memStore{
|
||||
conn: storage.Connection{URL: srv.URL, Passwordless: true},
|
||||
has: true,
|
||||
}
|
||||
func TestMultipleConnectionsAndSwitch(t *testing.T) {
|
||||
srvA := fakeServer(t, "", "", "Session A")
|
||||
srvB := fakeServer(t, "", "", "Session B")
|
||||
st := &memStore{conns: []storage.Connection{
|
||||
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 2},
|
||||
{ID: "b", URL: srvB.URL, Label: "B", Passwordless: true, LastUsedAt: 1},
|
||||
}}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("First session")
|
||||
a.ExpectNo("请重新输入密码")
|
||||
a.WaitFor("Session A")
|
||||
|
||||
a.Tap("断开")
|
||||
a.Expect("A")
|
||||
a.Expect("B")
|
||||
|
||||
a.Tap("B")
|
||||
a.WaitFor("Session B")
|
||||
}
|
||||
|
||||
func TestAddAnotherConnection(t *testing.T) {
|
||||
srvA := fakeServer(t, "", "", "Session A")
|
||||
srvB := fakeServer(t, "", "", "Session B")
|
||||
st := &memStore{conns: []storage.Connection{
|
||||
{ID: "a", URL: srvA.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
|
||||
}}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("Session A")
|
||||
a.Tap("断开")
|
||||
a.Tap("添加服务器")
|
||||
a.Type("http://192.168.1.5:3000", srvB.URL)
|
||||
a.Type("名称(可选)", "B")
|
||||
a.Tap("连接")
|
||||
a.WaitFor("Session B")
|
||||
|
||||
if conns := st.connections(); len(conns) != 2 {
|
||||
t.Fatalf("connections = %+v", conns)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteConnection(t *testing.T) {
|
||||
srv := fakeServer(t, "", "", "Session A")
|
||||
st := &memStore{conns: []storage.Connection{
|
||||
{ID: "a", URL: srv.URL, Label: "A", Passwordless: true, LastUsedAt: 1},
|
||||
}}
|
||||
a := mount(t, st)
|
||||
a.WaitFor("Session A")
|
||||
a.Tap("断开")
|
||||
|
||||
a.Tap("操作")
|
||||
a.Tap("删除")
|
||||
a.Tap("删除")
|
||||
a.Until("the connection list to empty", func() bool { return len(st.connections()) == 0 })
|
||||
a.Expect("手动输入地址")
|
||||
}
|
||||
+10
-62
@@ -10,65 +10,20 @@ import (
|
||||
"github.com/openchamber/openchamber-native/internal/ocapi"
|
||||
)
|
||||
|
||||
func (c *controller) connectScreen() ui.Node {
|
||||
return ui.Scroll(
|
||||
ui.ScrollProps{
|
||||
Style: ui.Style{Grow: 1},
|
||||
ContentStyle: ui.Style{Padding: ui.All(20), Gap: 14},
|
||||
},
|
||||
ui.StaticText("连接到 OpenChamber", ui.Style{Font: fonts.LargeTitle.Weighted(fonts.Bold)}),
|
||||
ui.StaticText("输入正在运行的 OpenChamber 服务器地址。没有设置密码的服务器可以留空密码。",
|
||||
ui.Style{Color: colors.SecondaryLabel}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.url,
|
||||
Placeholder: ui.Val("http://192.168.1.5:3000"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
ContentType: "url",
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
ReturnKey: ui.ReturnNext,
|
||||
}),
|
||||
ui.TextField(ui.TextFieldProps{
|
||||
Value: c.password,
|
||||
Placeholder: ui.Val("密码(可选)"),
|
||||
Secure: true,
|
||||
ContentType: ui.ContentPassword,
|
||||
ReturnKey: ui.ReturnGo,
|
||||
OnSubmit: c.connect,
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("使用代理", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.useProxy}),
|
||||
),
|
||||
ui.Show(c.useProxy, func() ui.Node {
|
||||
return ui.TextField(ui.TextFieldProps{
|
||||
Value: c.proxy,
|
||||
Placeholder: ui.Val("socks5://127.0.0.1:1080 或 http://127.0.0.1:7890"),
|
||||
Keyboard: ui.KeyboardURL,
|
||||
Autocapitalize: ui.CapitalizeNone,
|
||||
Autocorrect: ui.AutocorrectNo,
|
||||
})
|
||||
}),
|
||||
ui.Row(ui.Style{Align: ui.AlignCenter, Gap: 10},
|
||||
ui.StaticText("信任自签证书", ui.Style{Grow: 1}),
|
||||
ui.Toggle(ui.ToggleProps{Value: c.insecure}),
|
||||
),
|
||||
ui.Button(ui.ButtonProps{
|
||||
Title: ui.Val("连接"),
|
||||
Variant: ui.ButtonFilled,
|
||||
Disabled: c.busy,
|
||||
OnPress: c.connect,
|
||||
}),
|
||||
ui.Text(c.status, ui.Style{Color: colors.SecondaryLabel}),
|
||||
)
|
||||
}
|
||||
|
||||
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}),
|
||||
ui.Row(ui.Style{Padding: ui.Symmetric(8, 16), Gap: 4, Align: ui.AlignCenter},
|
||||
ui.Column(ui.Style{Grow: 1, Gap: 2},
|
||||
ui.Text(c.server, ui.Style{Font: fonts.Footnote, Color: colors.SecondaryLabel, Lines: 1}),
|
||||
ui.Show(signal.Func(func() bool { return c.errorMsg.Get() != "" }),
|
||||
func() ui.Node {
|
||||
return ui.Text(c.errorMsg, ui.Style{Font: fonts.Footnote, Color: colors.Red, Lines: 2})
|
||||
}),
|
||||
),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("实例"), Variant: ui.ButtonPlain,
|
||||
OnPress: func() { c.instancesOpen.Set(true) }}),
|
||||
ui.Button(ui.ButtonProps{Title: ui.Val("断开"), Variant: ui.ButtonPlain, OnPress: c.disconnect}),
|
||||
),
|
||||
ui.Show(signal.Func(func() bool { return len(c.sessions.Get()) == 0 }),
|
||||
@@ -103,13 +58,6 @@ func (c *controller) sessionsScreen() ui.Node {
|
||||
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) },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -169,6 +169,16 @@ func (c *controller) openNewSession() {
|
||||
c.newOpen.Set(true)
|
||||
}
|
||||
|
||||
func (c *controller) newSessionSheetNode() ui.Node {
|
||||
return ui.Sheet(ui.SheetProps{
|
||||
Open: c.newOpen,
|
||||
Detents: ui.DetentLarge,
|
||||
Grabber: true,
|
||||
Content: c.newSessionSheet,
|
||||
OnDismiss: func() { c.creating.Set(false) },
|
||||
})
|
||||
}
|
||||
|
||||
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)}),
|
||||
|
||||
Reference in new issue
Block a user