routing: a rule's hours over give the conversation back; looser times (MinglunZhu on X)
MinglunZhu asked twice for a provider by time of day and said the time setting in Routing rules is awkward. Three causes: - A conversation a night rule sent to its member stayed there after the hours: no rule matched the new turn, so Auto affinity kept it on the night's member by its cache (Smart and every routing but In order). ruleFor now sets RuleHit.Ended when the last turn's rule had hours that are over, and affine lets the conversation go (Affinity.Why "hours"); the trace says so in en, zh, zh-TW, ja, de. Tool rounds of a turn begun inside the hours stay put; Session, Strict and In turn keep their own way. - The time boxes took only ASCII "HH:MM", while their numeric keypad on a phone has no colon and a Chinese IME types ":". clockOf (GUI) and clockMinutes (CLI, saved files) now read "22", "2200", "930", "22:00", "22.00", "22点30" and full-width digits; "9:5" is still no time. time=22~08 takes ~ and ~ for the dash. - A new rule starts with an intent box; hours took an × and a +. Adding another condition now drops the intent box while it is empty. A time rule in a nested group doesn't give its conversation back yet: #5977. Run (mote): go test ./internal/provider (ok); go test -run 'TestRuleHoursOver|TestRuleTime|TestRule|Affinity|StandIn|Session|TestParse|Clock' ./internal/gateway (ok); go vet darwin, GOOS=linux -tags nogui, GOOS=windows for gateway and provider; gofmt. GUI, chromium and webkit: routing-time (8/8 after the new trace test's fix), and 28 rule/affinity/ i18n files (routing-rule-*, routing-time*, routing-intent-entry, routing-folder, routing-pause*, routing-smart-intent, routing-save*, routing-rules-line, routing-affinity-*, routing-behind-why, routing-kept-again, routing-session-folder, i18n-keys, i18n-en-no-cjk): 477/481, the 4 reds the new trace test's first wording, fixed and rerun. Broken by hand: affine's "hours" case off -> TestRuleHoursOverGiveThe ConversationBack red (Smart stays on kb by cache); origin's grouprule.go/ruleparse.go -> TestRuleTimeTypedLoosely red; client.js's "hours" case and the intent give-way off -> routing-time 0/4 in chromium; the old clockOf -> routing-time red on "9:00". Not tried: the real app with a real night/day pair of providers; the full gateway package and full GUI suite (the full Go suite runs after the tag); Windows run of the touched packages (vet only).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -117,7 +117,9 @@ type Affinity struct {
|
||||
// again at a new turn: backToFirst), "back" (a member of a group
|
||||
// routed any other way stood in for one listed ahead of it that
|
||||
// couldn't take the conversation, and a member ahead is ready first
|
||||
// at a new turn: backFromStandIn), "credits" (a Codex account gone
|
||||
// at a new turn: backFromStandIn), "hours" (a group's rule by hours
|
||||
// sent its last turn there and they are over: RuleHit.Ended),
|
||||
// "credits" (a Codex account gone
|
||||
// onto its credits answered it, set to spend them only after
|
||||
// everything else, and one not on its credits leads: lastBehind),
|
||||
// "busy" (its plugin says the model is busier than settings.BusyLoad
|
||||
@@ -559,7 +561,7 @@ func stickKey(scope string, in http.Header, body []byte) string {
|
||||
// more for each 4 MB Codex request in flight. inOrder: the request is to
|
||||
// a routing group, or a provider's keys or accounts, set to In order,
|
||||
// whose order the user chose (backToFirst).
|
||||
func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, from provider.Protocol, body, written []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {
|
||||
func affine(scope, mode string, rotate, spread, inOrder, hoursOver bool, in http.Header, from provider.Protocol, body, written []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {
|
||||
key := stickKey(scope, in, body)
|
||||
a := &Affinity{Mode: mode}
|
||||
a.Turn, a.Within = turnOf(from, written)
|
||||
@@ -667,6 +669,15 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr
|
||||
// its cache as before; within a turn it stays, and Stays:
|
||||
// Session or Strict, the user's own, keep it where it is
|
||||
a.Why = "back"
|
||||
case !a.Within && hoursOver && !rotate && mode == "" && at > 0:
|
||||
// a rule's hours sent the conversation's last turn here, and they
|
||||
// are over (RuleHit.Ended; MinglunZhu on X: a cheaper provider at
|
||||
// night, the usual one by day): the new turn goes where the group
|
||||
// routes it, whatever this one cached, or a conversation begun at
|
||||
// night stayed on the night's provider all day by its cache.
|
||||
// Within a turn it stays; Stays: Session and Strict, the user's
|
||||
// own, keep it where it is
|
||||
a.Why = "hours"
|
||||
case at > 0 && pl.order[at].Known && pl.order[at].Used >= provider.SpentShareOf(cs[at].p.Routing) && !pl.order[at].CreditsFirst:
|
||||
// all but used up, and put behind another: first still — the
|
||||
// one key or account it has (#1016), or every one used up — it
|
||||
|
||||
@@ -119,22 +119,22 @@ func TestBusyModelNotKeptAtNewTurn(t *testing.T) {
|
||||
h.Set("x-claude-code-session-id", "busy-load-kept")
|
||||
turn := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
within := []byte(`{"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{}"}}]},{"role":"tool","tool_call_id":"c1","content":"ok"}]}`)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, pl)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, turn, turn, cs, pl)
|
||||
answered(key, cs[1], 1, Usage{CacheRead: 50_000})
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, within, within, cs, pl)
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, within, within, cs, pl)
|
||||
if got[0].rest != "inhouse-plugin/big" || !aff.Kept {
|
||||
t.Fatalf("within a turn: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
|
||||
}
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, pl)
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, turn, turn, cs, pl)
|
||||
if got[0].rest != "inhouse-plugin/mid" || aff.Kept || aff.Why != "busy" {
|
||||
t.Fatalf("a new turn: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
// every one busy: kept where it was
|
||||
both := planned{order: []Weighed{{Who: "mid", Busy: 85}, {Who: "big", Busy: 92}}}
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, turn, turn, cs, both)
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, turn, turn, cs, both)
|
||||
if got[0].rest != "inhouse-plugin/big" || !aff.Kept {
|
||||
t.Fatalf("all busy: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestChatGPTConversationStaysPastFiveMinutes(t *testing.T) {
|
||||
// more left first, which after a turn on the last is the other
|
||||
cs := []candidate{c.next, c.last}
|
||||
pl := planned{order: []Weighed{{}, {}}}
|
||||
_, _, _, key := affine("t", "", false, false, false, h, provider.Responses, first, first, cs, pl)
|
||||
_, _, _, key := affine("t", "", false, false, false, false, h, provider.Responses, first, first, cs, pl)
|
||||
answered(key, c.last, 1, Usage{Input: 1200, CacheRead: 20000, CacheWrite: 1200})
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
sticks.Lock()
|
||||
@@ -50,7 +50,7 @@ func TestChatGPTConversationStaysPastFiveMinutes(t *testing.T) {
|
||||
st.at = st.at.Add(-c.ago)
|
||||
sticks.m[key] = st
|
||||
sticks.Unlock()
|
||||
got, _, a, _ := affine("t", "", false, false, false, h, provider.Responses, again, again, cs, pl)
|
||||
got, _, a, _ := affine("t", "", false, false, false, false, h, provider.Responses, again, again, cs, pl)
|
||||
if a.Why != c.why || a.Kept != (c.why == "cache") {
|
||||
t.Fatalf("%s: why %q kept %v, want %q", c.name, a.Why, a.Kept, c.why)
|
||||
}
|
||||
|
||||
@@ -114,17 +114,17 @@ func TestCodexCreditsLastNotKept(t *testing.T) {
|
||||
h := http.Header{}
|
||||
h.Set("x-claude-code-session-id", "credits-last-kept")
|
||||
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
answered(key, cs[1], 1, Usage{CacheRead: 50_000})
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
if got[0].rest != "codex/spare@example.com" || aff.Kept || aff.Why != "credits" {
|
||||
t.Fatalf("first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
// every one on its credits and last: kept where it was
|
||||
both := planned{order: []Weighed{{Who: "spare@example.com", CreditsLast: true}, {Who: "me@example.com", CreditsLast: true}}}
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, both)
|
||||
got, _, aff, _ = affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, body, body, cs, both)
|
||||
if got[0].rest != "codex/me@example.com" || !aff.Kept {
|
||||
t.Fatalf("all last: first %s, kept %v, why %s", got[0].rest, aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestDeepSeekConversationStaysPastFiveMinutes(t *testing.T) {
|
||||
h.Set("x-claude-code-session-id", "deepseek-cold-"+string(rune('a'+i)))
|
||||
cs := []candidate{c.next, c.last}
|
||||
pl := planned{order: []Weighed{{}, {}}}
|
||||
_, _, _, key := affine("t", "", false, false, false, h, provider.Anthropic, first, first, cs, pl)
|
||||
_, _, _, key := affine("t", "", false, false, false, false, h, provider.Anthropic, first, first, cs, pl)
|
||||
answered(key, c.last, 1, Usage{Input: 300, CacheRead: 13696})
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
sticks.Lock()
|
||||
@@ -48,7 +48,7 @@ func TestDeepSeekConversationStaysPastFiveMinutes(t *testing.T) {
|
||||
st.at = st.at.Add(-c.ago)
|
||||
sticks.m[key] = st
|
||||
sticks.Unlock()
|
||||
got, _, a, _ := affine("t", "", false, false, false, h, provider.Anthropic, again, again, cs, pl)
|
||||
got, _, a, _ := affine("t", "", false, false, false, false, h, provider.Anthropic, again, again, cs, pl)
|
||||
if a.Why != c.why || a.Kept != (c.why == "cache") {
|
||||
t.Fatalf("%s: why %q kept %v, want %q", c.name, a.Why, a.Kept, c.why)
|
||||
}
|
||||
|
||||
@@ -3135,7 +3135,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
if isGroup {
|
||||
inOrder = routingOf(g.Routing) == provider.Ordered
|
||||
}
|
||||
cands, pl, aff, stuck := affine(scope, mode, rotate, spread, inOrder, r.Header, from, body, plain, cands, pl)
|
||||
cands, pl, aff, stuck := affine(scope, mode, rotate, spread, inOrder, hit != nil && hit.Ended > 0, r.Header, from, body, plain, cands, pl)
|
||||
// a strict conversation left with its own account of several: its
|
||||
// failure rests the account as it would with the others still there,
|
||||
// for new conversations to go elsewhere meanwhile (#1797)
|
||||
|
||||
@@ -30,13 +30,13 @@ func TestLoginSwitchKeepsEachAccountItself(t *testing.T) {
|
||||
h.Set("x-claude-code-session-id", "login-switch-209")
|
||||
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
pl := planned{order: make([]Weighed, 2)}
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Anthropic, body, body, []candidate{a, b}, pl)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Anthropic, body, body, []candidate{a, b}, pl)
|
||||
answered(key, a, 1, Usage{})
|
||||
servedCandidate(a, 5000)
|
||||
|
||||
// signed in to b now
|
||||
a2, b2 := acct("a@example.com", "claude@a@example.com"), acct("b@example.com", "claude")
|
||||
cs, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Anthropic, body, body, []candidate{b2, a2}, planned{order: make([]Weighed, 2)})
|
||||
cs, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Anthropic, body, body, []candidate{b2, a2}, planned{order: make([]Weighed, 2)})
|
||||
if cs[0].p.Account.User != "a@example.com" || !aff.Kept {
|
||||
t.Fatalf("the conversation went to %s (kept %v, %s)", cs[0].p.Account.User, aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
@@ -69,10 +69,10 @@ func TestLoneSpentKeyKeepsItsConversation(t *testing.T) {
|
||||
h := http.Header{}
|
||||
h.Set("x-claude-code-session-id", "lone-spent-1016")
|
||||
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
_, _, _, key := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
answered(key, c, 1, Usage{})
|
||||
t.Cleanup(func() { sticks.Lock(); delete(sticks.m, key); sticks.Unlock() })
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
got, _, aff, _ := affine("t", provider.AffinitySession, false, false, false, false, h, provider.Chat, body, body, cs, pl)
|
||||
if got[0].rest != "kimi-code-cn" || aff.Why == "spent" || !aff.Kept {
|
||||
t.Fatalf("kept %v, why %s", aff.Kept, aff.Why)
|
||||
}
|
||||
|
||||
@@ -72,6 +72,13 @@ type RuleHit struct {
|
||||
Small []string `json:"small,omitempty"`
|
||||
// Bare: the group has no rules, only its effort picked
|
||||
Bare bool `json:"bare,omitempty"`
|
||||
// Ended: the rule (from 1) that sent the conversation's last turn to
|
||||
// its member held by hours that are over now (MinglunZhu on X: a
|
||||
// cheaper provider at night, the usual one by day). No rule puts a
|
||||
// member first this turn, and the vendor's cache of the night's member
|
||||
// doesn't keep the conversation there (affine's "hours"): it goes
|
||||
// where the group routes it, as a new conversation would
|
||||
Ended int `json:"ended,omitempty"`
|
||||
// UseEffort: the reasoning the rule asks the member it names for
|
||||
// (provider.Rule.UseEffort, #2633), in place of the agent's
|
||||
UseEffort string `json:"useEffort,omitempty"`
|
||||
@@ -374,6 +381,11 @@ func ruleFor(key string, g provider.Group, ms []provider.Member, req *Request, a
|
||||
if i := provider.MatchRule(g.Rules, q); i >= 0 {
|
||||
hit.N, hit.Use, hit.More, hit.When = i+1, g.Rules[i].Use, g.Rules[i].More, g.Rules[i].Conditions()
|
||||
}
|
||||
if had && hit.Use == "" && tr.use != "" && tr.n >= 1 && tr.n <= len(g.Rules) {
|
||||
if r := g.Rules[tr.n-1]; r.Use == tr.use && r.Time != nil && !r.Time.Holds(now) {
|
||||
hit.Ended = tr.n
|
||||
}
|
||||
}
|
||||
turnRules.Lock()
|
||||
defer turnRules.Unlock()
|
||||
input, answered, hour := tr.input, tr.answered, tr.hour
|
||||
|
||||
@@ -10,8 +10,9 @@ import (
|
||||
|
||||
// A rule's hours are looked at as a turn begins, on the clock then: a turn
|
||||
// begun inside them goes to its member and stays there for its tool
|
||||
// rounds after they end; a turn begun outside them isn't the rule's (where
|
||||
// the same conversation goes then is the group's Stays to say).
|
||||
// rounds after they end; a turn begun outside them isn't the rule's (and the
|
||||
// conversation goes where the group routes it then:
|
||||
// TestRuleHoursOverGiveTheConversationBack).
|
||||
func TestRuleTimeWindowAtTurnStart(t *testing.T) {
|
||||
now := time.Date(2026, 9, 29, 10, 0, 0, 0, time.Local) // a Tuesday
|
||||
ruleClock = func() time.Time { return now }
|
||||
@@ -115,3 +116,65 @@ func TestRuleTimeWindowInItsZoneAtTurnStart(t *testing.T) {
|
||||
t.Fatalf("a %d b %d", a.n(), b.n())
|
||||
}
|
||||
}
|
||||
|
||||
// A conversation a rule's hours sent to its member goes where the group
|
||||
// routes it once they are over, whatever that member cached (MinglunZhu on
|
||||
// X: a cheaper provider at night, the usual one by day). Kept by its cache,
|
||||
// a Claude Code session begun at night stayed on the night's provider all
|
||||
// day in a group routed Smart. Session, the user's own, keeps it.
|
||||
func TestRuleHoursOverGiveTheConversationBack(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
routing, mode, day string // where turn 2, by day, goes
|
||||
why string
|
||||
}{
|
||||
{"", "", "from ka", "hours"},
|
||||
{"", provider.AffinitySession, "from kb", "session"},
|
||||
} {
|
||||
t.Run(tc.routing+"/"+tc.mode, func(t *testing.T) {
|
||||
now := time.Date(2026, 9, 29, 23, 0, 0, 0, time.Local) // a Tuesday night
|
||||
ruleClock = func() time.Time { return now }
|
||||
t.Cleanup(func() { ruleClock = time.Now })
|
||||
night := provider.Rule{Use: "b/big", Time: &provider.TimeWindow{From: "22:00", To: "08:00"}}
|
||||
s, a, b := ruled(t, night)
|
||||
g := provider.Group{Name: "R", Members: []string{"a/small", "b/big"}, Routing: tc.routing, Affinity: tc.mode, Rules: []provider.Rule{night}}
|
||||
if err := provider.SaveGroup(g); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
post := func(body string) (string, Route) {
|
||||
t.Helper()
|
||||
code, out := postAs(t, s, "sess", body)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, out)
|
||||
}
|
||||
return out, lastRoute(s)
|
||||
}
|
||||
// turn 1, at night: the rule's member
|
||||
if out, r := post(chat("hello", nil, 0, "")); !strings.Contains(out, "from kb") || r.Rule.N != 1 {
|
||||
t.Fatalf("night: %s %+v", out, r.Rule)
|
||||
}
|
||||
// its tool round past 08:00 stays where the turn began
|
||||
now = time.Date(2026, 9, 30, 8, 1, 0, 0, time.Local)
|
||||
if out, r := post(chat("hello", nil, 1, "")); !strings.Contains(out, "from kb") || !r.Rule.Held {
|
||||
t.Fatalf("tool round: %s %+v", out, r.Rule)
|
||||
}
|
||||
// turn 2, by day, a minute later: the vendor read 2500 tokens of
|
||||
// it from its cache, and the hours are over
|
||||
now = time.Date(2026, 9, 30, 8, 2, 0, 0, time.Local)
|
||||
out, r := post(chat("hello", []string{"more"}, 0, ""))
|
||||
if !strings.Contains(out, tc.day) || r.Rule.N != 0 || r.Affinity == nil || r.Affinity.Why != tc.why {
|
||||
t.Fatalf("day: %s rule %+v affinity %+v", out, r.Rule, r.Affinity)
|
||||
}
|
||||
if tc.why == "hours" && r.Rule.Ended != 1 {
|
||||
t.Fatalf("the trace names the rule whose hours ended: %+v", r.Rule)
|
||||
}
|
||||
// and the day's turns after it keep the day's member by its cache
|
||||
out, r = post(chat("hello", []string{"more", "again"}, 0, ""))
|
||||
if !strings.Contains(out, tc.day) || r.Rule.Ended != 0 {
|
||||
t.Fatalf("turn 3: %s rule %+v affinity %+v", out, r.Rule, r.Affinity)
|
||||
}
|
||||
if a.n()+b.n() != 4 {
|
||||
t.Fatalf("a %d b %d", a.n(), b.n())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestSessionSideCallFollowsItsMain(t *testing.T) {
|
||||
}
|
||||
run := func(mode string, body []byte) ([]candidate, *Affinity) {
|
||||
cs := []candidate{key("k1"), key("k2")}
|
||||
got, _, aff, _ := affine("sx/m2", mode, false, false, false, h, provider.Chat, body, body, cs, planned{order: make([]Weighed, 2)})
|
||||
got, _, aff, _ := affine("sx/m2", mode, false, false, false, false, h, provider.Chat, body, body, cs, planned{order: make([]Weighed, 2)})
|
||||
return got, aff
|
||||
}
|
||||
t.Run("new turn", func(t *testing.T) {
|
||||
@@ -130,7 +130,7 @@ func TestSessionSideCallFollowsItsMain(t *testing.T) {
|
||||
delete(sticks.m, "sx/m1|"+hashed)
|
||||
sticks.Unlock()
|
||||
})
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, http.Header{}, provider.Chat, turn, turn, cs, planned{order: make([]Weighed, 2)})
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, false, http.Header{}, provider.Chat, turn, turn, cs, planned{order: make([]Weighed, 2)})
|
||||
if got[0].rest != "sx#k2" || aff.Why != "cache" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
@@ -147,7 +147,7 @@ func TestSessionSideCallFollowsItsMain(t *testing.T) {
|
||||
set(t, 60_000, 120_000)
|
||||
cs := []candidate{key("k2"), key("k1")}
|
||||
order := []Weighed{{}, {Rest: &Rest{}}}
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, h, provider.Chat, turn, turn, cs, planned{order: order})
|
||||
got, _, aff, _ := affine("sx/m2", "", false, false, false, false, h, provider.Chat, turn, turn, cs, planned{order: order})
|
||||
if got[0].rest != "sx#k2" || aff.Why != "cache" {
|
||||
t.Errorf("first %s, why %s; want kept on sx#k2", got[0].rest, aff.Why)
|
||||
}
|
||||
|
||||
@@ -1147,6 +1147,7 @@ function routingPage(part) {
|
||||
: t("{who} answered this conversation last, but the provider goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.", { who: last, first: who(r.order[0]), n: a.turn });
|
||||
case "main": return t("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.", { who: last, first: who(r.order[0]), n: a.turn });
|
||||
case "back": return t("{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.", { who: last, first: who(r.order[0]), n: a.turn });
|
||||
case "hours": return t("{who} answered this conversation last, by rule {rule}, but the rule's hours are over, so turn {n} goes where the group routes it.", { who: last, rule: r.rule?.ended, n: a.turn });
|
||||
case "no-cache": return t("{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.", { who: last, r: tokens(a.cacheRead || 0), w: tokens(a.cacheWrite || 0) });
|
||||
case "cold": return t("{who} answered this conversation {d} ago, longer than the 5 minutes a vendor keeps a prompt cached — so routing decides afresh.", { who: last, d: ago });
|
||||
case "off": return t("Affinity is off: each request is routed afresh, whoever answered its conversation before.");
|
||||
@@ -1373,10 +1374,14 @@ function routingPage(part) {
|
||||
}
|
||||
return -new Date().getTimezoneOffset() === server ? "" : t("server time, {offset}", { offset: utcText(server) });
|
||||
}
|
||||
// "9:5" is no time; "9:05" is 09:05
|
||||
// "9:5" is no time; "9:05" is 09:05. What a phone's number pad or a
|
||||
// Chinese keyboard types counts too (MinglunZhu on X): "22", "2200",
|
||||
// "930", "22:00", "22.00", "22点", "22点30".
|
||||
const clockOf = (s) => {
|
||||
const m = /^\s*(\d{1,2}):(\d{2})\s*$/.exec(s || "");
|
||||
return m && +m[1] < 24 && +m[2] < 60 ? m[1].padStart(2, "0") + ":" + m[2] : "";
|
||||
const v = String(s || "").replace(/[\uff10-\uff19]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 0xfee0)).trim();
|
||||
const m = /^(\d{1,2})(?:[::..h時时点點]\s*(\d{2})?分?)?$/i.exec(v) || /^(\d{1,2})(\d{2})$/.exec(v);
|
||||
const h = m?.[1], mm = m?.[2] ?? "00";
|
||||
return m && +h < 24 && +mm < 60 ? h.padStart(2, "0") + ":" + mm : "";
|
||||
};
|
||||
|
||||
// how the reasoning a try was sent at came to be
|
||||
@@ -7950,6 +7955,9 @@ function routingPage(part) {
|
||||
// a condition taken off is the value saved for none, as before
|
||||
const condNone = { intent: "", tokens: 0, images: false, effort: "", compact: false, agents: [], folders: [], exceptFolders: [], time: null };
|
||||
const addCond = (r, k) => {
|
||||
// a new rule's intent box left empty gives way to the condition
|
||||
// picked instead (MinglunZhu on X: hours took an × and a +)
|
||||
if (k !== "intent" && !r.intent?.trim()) openedOf(r).delete("intent");
|
||||
openedOf(r).add(k);
|
||||
if (k === "images" || k === "compact") r[k] = true;
|
||||
if (k === "subagent") setWhere(r, "subagent", { op: "is" });
|
||||
|
||||
@@ -661,6 +661,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but the provider goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此会话上次由 {who} 回答,但该提供商按顺序路由,排在它前面的 {first} 已恢复可用,所以第 {n} 轮回到 {first}。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此会话上次由备用 {who} 回答,但提供商自己的 {first} 已恢复可用,所以第 {n} 轮回到它。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "此会话由 {who} 接手,当时组里排在它前面的 {first} 无法处理;{first} 已恢复可用,所以第 {n} 轮回到它。",
|
||||
"{who} answered this conversation last, by rule {rule}, but the rule's hours are over, so turn {n} goes where the group routes it.": "{who} 上次回答了此会话,依据的是规则 {rule},但该规则的时段已过,所以第 {n} 轮按组的路由方式重新选择。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此会话上次由备用 {who} 回答。提供商自己的 {first} 已恢复可用,但会话保持设为严格,从不移动会话,所以它留在备用上;新会话会走 {first}。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "放在 {first} 上,也就是这个会话的 {model} 所在的账号:一个会话只走一个账号。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此会话上次由 {who} 回答,但当时厂商只从缓存读取了 {r} tokens、写入了 {w} tokens,不值得保留。",
|
||||
@@ -1395,6 +1396,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but the provider goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "此會話上次由 {who} 回答,但該供應商按順序路由,排在它前面的 {first} 已恢復可用,所以第 {n} 輪回到 {first}。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "此會話上次由備用 {who} 回答,但供應商自己的 {first} 已恢復可用,所以第 {n} 輪回到它。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "此會話由 {who} 接手,當時群組裡排在它前面的 {first} 無法處理;{first} 已恢復可用,所以第 {n} 輪回到它。",
|
||||
"{who} answered this conversation last, by rule {rule}, but the rule's hours are over, so turn {n} goes where the group routes it.": "{who} 上次回答了此會話,依據的是規則 {rule},但該規則的時段已過,所以第 {n} 輪按群組的路由方式重新選擇。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "此會話上次由備用 {who} 回答。供應商自己的 {first} 已恢復可用,但會話保持設為嚴格,從不移動會話,所以它留在備用上;新會話會走 {first}。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "放在 {first} 上,也就是這個會話的 {model} 所在的帳號:一個會話只走一個帳號。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "此會話上次由 {who} 回答,但當時廠商只從快取讀取了 {r} tokens、寫入了 {w} tokens,不值得保留。",
|
||||
@@ -2127,6 +2129,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but the provider goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "この会話に前回応答したのは {who} ですが、このプロバイダーは順番どおりにルーティングし、その前にある {first} が再び使えるため、ターン {n} は {first} に戻ります。",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "この会話に前回応答したのは代替の {who} ですが、プロバイダー自身の {first} が再び使えるため、ターン {n} はそちらに戻ります。",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "この会話は、グループでその前にある {first} が受けられなかったため {who} が引き継ぎました。{first} が再び使えるため、ターン {n} はそちらに戻ります。",
|
||||
"{who} answered this conversation last, by rule {rule}, but the rule's hours are over, so turn {n} goes where the group routes it.": "この会話に前回答えたのはルール {rule} による {who} ですが、そのルールの時間帯は終わったため、ターン {n} はグループのルーティングに従います。",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "この会話に前回応答したのは代替の {who} です。プロバイダー自身の {first} は再び使えますが、維持が「厳格」で会話を移さないため、代替のままです。新しい会話は {first} に行きます。",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "このセッションの {model} がいる {first} に置きました。1 つのセッションは 1 つのアカウントで動きます。",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "この会話に前回応答したのは {who} ですが、そのときベンダーがキャッシュから読んだのは {r} トークン、書き込んだのは {w} トークンだけでした — 留まる価値はありません。",
|
||||
@@ -2861,6 +2864,7 @@ magpie.strings({
|
||||
"{who} answered this conversation last, but the provider goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber der Anbieter geht der Reihe nach vor und {first}, das davor steht, ist wieder bereit, daher geht Runde {n} zurück an {first}.",
|
||||
"{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet, aber {first} des Anbieters selbst ist wieder bereit, daher geht Runde {n} dorthin zurück.",
|
||||
"{who} took this conversation while {first}, listed ahead of it in the group, couldn't; {first} is ready again, so turn {n} goes back to it.": "{who} hat diese Unterhaltung übernommen, als {first}, in der Gruppe davor, sie nicht annehmen konnte; {first} ist wieder bereit, daher geht Runde {n} dorthin zurück.",
|
||||
"{who} answered this conversation last, by rule {rule}, but the rule's hours are over, so turn {n} goes where the group routes it.": "{who} hat diese Unterhaltung zuletzt beantwortet, nach Regel {rule}, aber deren Zeiten sind vorbei, daher geht Runde {n} dorthin, wohin die Gruppe leitet.",
|
||||
"{who}, a fallback, answered this conversation last. The provider's own {first} is ready again, but Stays is Strict, which never moves a conversation, so it stays on the fallback; new conversations go to {first}.": "{who}, ein Ersatz, hat diese Unterhaltung zuletzt beantwortet. {first} des Anbieters selbst ist wieder bereit, aber Bleibt steht auf Strikt, das eine Unterhaltung nie verschiebt, daher bleibt sie beim Ersatz; neue Unterhaltungen gehen an {first}.",
|
||||
"Put on {first}, where this session's {model} is: one session goes on one account.": "Auf {first} gelegt, wo das {model} dieser Sitzung läuft: eine Sitzung bleibt auf einem Konto.",
|
||||
"{who} answered this conversation last, but the vendor then read only {r} tokens of it from its cache and wrote {w} — not worth staying for.": "{who} hat diese Unterhaltung zuletzt beantwortet, aber der Anbieter hat damals nur {r} Token davon aus seinem Cache gelesen und {w} hineingeschrieben – das lohnt das Bleiben nicht.",
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
// times typed into one pill, past midnight noted, the days picked like the
|
||||
// agents, a time that isn't one marked, nothing moved by a click, and they
|
||||
// are saved as time:{from,to,days}, with the browser's zone when typed.
|
||||
// In English and Chinese.
|
||||
// A time typed as a phone's number pad or a Chinese keyboard gives it
|
||||
// ("9:00", "18") is that time, and the hours take a new rule's empty
|
||||
// intent box's place (MinglunZhu on X: the time was awkward to set). A
|
||||
// conversation a rule's hours sent somewhere goes where the group routes
|
||||
// it once they are over, and the trace says so. In English and Chinese.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
@@ -34,13 +38,21 @@ const route = {
|
||||
tries: [{ id: "b", model: "other", start: new Date(now - 2000).toISOString(), done: true, ms: 800, status: 200 }],
|
||||
rule: { n: 1, use: "b/other", when: ["time 22:00–08:00 Mon–Fri"], turn: 2, tokens: 9000 },
|
||||
};
|
||||
|
||||
const words = {
|
||||
en: { cond: "22:00–08:00 Mon–Fri", story: "rule 1 matches — 22:00–08:00 Mon–Fri —", night: "runs past midnight, into the next day", every: "every day", weekdays: "weekdays", sat: "Sat", monSat: "Mon–Sat", edit: "Edit", add: "Add a rule", save: "Save", hours: "Hours and days" },
|
||||
zh: { cond: "周一–周五 22:00–08:00", story: "规则 1", night: "跨过午夜,到第二天", every: "每天", weekdays: "工作日", sat: "周六", monSat: "周一–周六", edit: "编辑", add: "添加规则", save: "保存", hours: "时段" },
|
||||
// the morning after: no rule matches, and the night's member gives it back
|
||||
const morning = {
|
||||
...route, id: 8, seq: 8, provider: "a",
|
||||
order: [route.order[1], route.order[0]],
|
||||
tries: [{ id: "a", model: "glm", start: new Date(now - 2000).toISOString(), done: true, ms: 800, status: 200 }],
|
||||
affinity: { why: "hours", last: "b", turn: 3 },
|
||||
rule: { turn: 3, tokens: 9000, ended: 1 },
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
const words = {
|
||||
en: { cond: "22:00–08:00 Mon–Fri", story: "rule 1 matches — 22:00–08:00 Mon–Fri —", night: "runs past midnight, into the next day", every: "every day", weekdays: "weekdays", sat: "Sat", monSat: "Mon–Sat", edit: "Edit", add: "Add a rule", save: "Save", hours: "Hours and days", over: "by rule 1, but the rule's hours are over, so turn 3 goes where the group routes it." },
|
||||
zh: { cond: "周一–周五 22:00–08:00", story: "规则 1", night: "跨过午夜,到第二天", every: "每天", weekdays: "工作日", sat: "周六", monSat: "周一–周六", edit: "编辑", add: "添加规则", save: "保存", hours: "时段", over: "依据的是规则 1,但该规则的时段已过,所以第 3 轮" },
|
||||
};
|
||||
|
||||
function serve(lang, posts, routes = [route]) {
|
||||
const state = { agents: [{ id: "claude", name: "Claude Code", path: "/test/claude", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
|
||||
let first = true;
|
||||
return async (r) => {
|
||||
@@ -51,9 +63,9 @@ function serve(lang, posts) {
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
|
||||
const routes = first ? [route] : [];
|
||||
const out = first ? routes : [];
|
||||
first = false;
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 7, totals: { requests: 1, rerouted: 0, errors: 0 }, routes });
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: routes.at(-1).seq, totals: { requests: routes.length, rerouted: 0, errors: 0 }, routes: out });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
@@ -123,15 +135,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await wheelTo(addBtn);
|
||||
await addBtn.click();
|
||||
const row2 = rows.nth(1);
|
||||
// a new rule asks for an intent; the hours take its place, added
|
||||
// from the rule's + menu
|
||||
// a new rule asks for an intent; the hours, added from the rule's +
|
||||
// menu, take the empty box's place
|
||||
assert.equal(await row2.locator(".rt-cond.tm").count(), 0, "no hours until they are added");
|
||||
await row2.locator('.rt-c[data-k="intent"]').hover();
|
||||
await row2.locator('.rt-c[data-k="intent"] .rt-cx').click();
|
||||
assert.equal(await row2.locator('.rt-c[data-k="intent"]').count(), 1);
|
||||
await row2.locator(".rt-addc").click();
|
||||
await page.locator(".proto-menu .pm-item", { hasText: w.hours }).click();
|
||||
const tm2 = row2.locator(".rt-cond.tm");
|
||||
await tm2.waitFor();
|
||||
assert.equal(await row2.locator('.rt-c[data-k="intent"]').count(), 0, "the empty intent gave way to the hours");
|
||||
const dayBtn2 = row2.locator("button.rt-cond", { hasText: w.every });
|
||||
assert.equal(await dayBtn2.isVisible(), true, "the days beside the hours, every day until picked");
|
||||
const at = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop).map((e) => [e.id || e.className, e.scrollTop]).join(";") + "|" + Math.round(document.querySelector(".rt-gedit").getBoundingClientRect().top));
|
||||
@@ -147,10 +159,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await to2.click();
|
||||
assert.match(await tm2.getAttribute("class"), /\bbad\b/, "a time that isn't one is marked once left");
|
||||
assert.equal(await at(), before, "the click moved nothing");
|
||||
await from2.fill("9:00");
|
||||
await to2.fill("18:00");
|
||||
// typed as a Chinese keyboard and a phone's number pad give them
|
||||
await from2.fill("9:00");
|
||||
await to2.fill("18");
|
||||
await to2.blur();
|
||||
assert.equal(await from2.inputValue(), "09:00");
|
||||
assert.equal(await to2.inputValue(), "18:00");
|
||||
assert.equal(await tm2.getAttribute("class"), "rt-cond tm on");
|
||||
assert.equal(await row2.locator(".rt-rwarn").textContent(), "");
|
||||
|
||||
@@ -182,5 +196,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: the rule's hours over, the conversation goes back`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, timezoneId: "Asia/Shanghai" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, [], [morning]));
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
// the caption under the stage tells it
|
||||
const said = () => document.body.innerText + "\n" + (document.querySelector(".rt-cap")?.textContent || "");
|
||||
await page.waitForFunction((s) => (document.body.innerText + "\n" + (document.querySelector(".rt-cap")?.textContent || "")).includes(s), w.over)
|
||||
.catch(async (e) => { throw new Error(`${e.message}: ${await page.evaluate(said)}`); });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,20 +238,55 @@ var Weekdays = []string{"sun", "mon", "tue", "wed", "thu", "fri", "sat"}
|
||||
// dayOrder is the week as a window shows it, Monday first.
|
||||
var dayOrder = []string{"mon", "tue", "wed", "thu", "fri", "sat", "sun"}
|
||||
|
||||
// clockMinutes reads "HH:MM" (or "H:MM") as minutes past midnight.
|
||||
// clockMinutes reads "HH:MM" (or "H:MM") as minutes past midnight. What a
|
||||
// phone's number pad or a Chinese keyboard types counts too, as the GUI's
|
||||
// clockOf reads it (MinglunZhu on X): "22", "2200", "930", "22:00",
|
||||
// "22.00", "22点", "22点30". "9:5" is no time.
|
||||
func clockMinutes(s string) (int, bool) {
|
||||
h, m, ok := strings.Cut(strings.TrimSpace(s), ":")
|
||||
if !ok || len(h) < 1 || len(h) > 2 || len(m) != 2 {
|
||||
var b strings.Builder
|
||||
for _, r := range strings.TrimSpace(s) {
|
||||
switch {
|
||||
case r >= '0' && r <= '9':
|
||||
b.WriteRune(r - '0' + '0')
|
||||
case strings.ContainsRune("::..hH時时点點", r):
|
||||
b.WriteByte(':')
|
||||
case r == '分':
|
||||
default:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
v := b.String()
|
||||
h, m, ok := strings.Cut(v, ":")
|
||||
if !ok && len(v) >= 3 {
|
||||
h, m = v[:len(v)-2], v[len(v)-2:]
|
||||
}
|
||||
m = strings.TrimSpace(m)
|
||||
if ok && m == "" {
|
||||
m = "00"
|
||||
}
|
||||
if !ok && len(v) <= 2 {
|
||||
m = "00"
|
||||
}
|
||||
if len(h) < 1 || len(h) > 2 || len(m) != 2 || !digits(h) || !digits(m) {
|
||||
return 0, false
|
||||
}
|
||||
hh, err1 := strconv.Atoi(h)
|
||||
mm, err2 := strconv.Atoi(m)
|
||||
if err1 != nil || err2 != nil || hh < 0 || hh > 23 || mm < 0 || mm > 59 || h[0] == '+' || m[0] == '+' {
|
||||
hh, _ := strconv.Atoi(h)
|
||||
mm, _ := strconv.Atoi(m)
|
||||
if hh > 23 || mm > 59 {
|
||||
return 0, false
|
||||
}
|
||||
return hh*60 + mm, true
|
||||
}
|
||||
|
||||
func digits(s string) bool {
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return s != ""
|
||||
}
|
||||
|
||||
// ParseDay reads a day of the week, "mon" or "Monday", as Weekdays has it.
|
||||
func ParseDay(s string) (string, bool) {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
|
||||
@@ -71,7 +71,10 @@ func TestRuleTimeCleanAndConditions(t *testing.T) {
|
||||
}
|
||||
for _, bad := range []TimeWindow{
|
||||
{From: "25:00", To: "08:00"},
|
||||
{From: "09:00", To: "8"},
|
||||
{From: "09:00", To: "8:5"},
|
||||
{From: "09:00", To: "8 pm"},
|
||||
{From: "24", To: "08:00"},
|
||||
{From: "12345", To: "08:00"},
|
||||
{From: "", To: "08:00"},
|
||||
{From: "09:60", To: "10:00"},
|
||||
{From: "09:00", To: "18:00", Days: []string{"funday"}},
|
||||
@@ -83,6 +86,28 @@ func TestRuleTimeCleanAndConditions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Hours as a phone's number pad or a Chinese keyboard types them are the
|
||||
// same hours (MinglunZhu on X: setting the time in a rule was awkward).
|
||||
func TestRuleTimeTypedLoosely(t *testing.T) {
|
||||
for typed, want := range map[string]string{
|
||||
"22": "22:00", "8": "08:00", "2200": "22:00", "930": "09:30", "22:00": "22:00",
|
||||
"22.30": "22:30", "22:30": "22:30", "22点": "22:00", "22点30": "22:30", "8点30分": "08:30",
|
||||
"22h": "22:00", "9:00": "09:00", " 07:05 ": "07:05", "22:": "22:00",
|
||||
} {
|
||||
w := TimeWindow{From: typed, To: "12:00"}
|
||||
if err := w.clean(); err != nil || w.From != want {
|
||||
t.Errorf("%q: %q %v, want %q", typed, w.From, err, want)
|
||||
}
|
||||
}
|
||||
if w, err := ParseTimeWindow("9-18"); err != nil || w.From != "09:00" || w.To != "18:00" {
|
||||
t.Errorf("time=9-18: %+v %v", w, err)
|
||||
}
|
||||
w, err := ParseTimeWindow("22~8")
|
||||
if err != nil || w.From != "22:00" || w.To != "08:00" {
|
||||
t.Errorf("time=22~8: %+v %v", w, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A rule with hours matches a request inside them only; one without a
|
||||
// time (an older magpie's) is in none.
|
||||
func TestRuleTimeMatches(t *testing.T) {
|
||||
@@ -143,7 +168,7 @@ func TestParseRuleTime(t *testing.T) {
|
||||
t.Errorf("%s: read back %v %+v", c.line, err, again.Time)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"use=b/y time=9-18", "use=b/y time=09:00", "use=b/y days=someday", "use=b/y days="} {
|
||||
for _, bad := range []string{"use=b/y time=9:5-18", "use=b/y time=09:00", "use=b/y days=someday", "use=b/y days="} {
|
||||
if _, _, _, err := ParseRule(g, RuleWords(bad)); err == nil {
|
||||
t.Errorf("%s: no error", bad)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func ParseDays(v string) ([]string, error) {
|
||||
// the time zone they are in after an @: 09:00-18:00@Asia/Shanghai.
|
||||
func ParseTimeWindow(v string) (*TimeWindow, error) {
|
||||
hours, zone, _ := strings.Cut(v, "@")
|
||||
from, to, ok := strings.Cut(strings.ReplaceAll(strings.TrimSpace(hours), "–", "-"), "-")
|
||||
from, to, ok := strings.Cut(strings.NewReplacer("–", "-", "~", "-", "~", "-").Replace(strings.TrimSpace(hours)), "-")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("time is hours of the day: time=09:00-18:00 (or 22:00-08:00, past midnight; 09:00-18:00@Asia/Shanghai in a time zone), not %q", v)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user